-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathlogging-in-single-sign-on-spec.cy.js
267 lines (220 loc) · 9.21 KB
/
logging-in-single-sign-on-spec.cy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/// <reference types="cypress" />
// This recipe expands on the previous 'Logging in' examples
// and shows you how to login when authentication is done
// through a 3rd party server.
// There is a web security restriction in Cypress that prevents
// you from visiting two different super domains in the same test
// without setting {chromeWebSecurity: false} in cypress.config.js.
// However this restriction is easy to bypass (and is much more
// performant and less brittle) with cy.request
// There are two servers in use in this example.
// 1. http://localhost:7074 (the app server)
// 2. http://auth.corp.com:7075 (the authentication server)
// Be sure to run `npm start` to start the server
// before running the tests below.
// NOTE: We are able to use auth.corp.com without modifying our
// local /etc/hosts file because cypress supports hosts mapping
// in cypress.config.js
// Most 3rd party authentication works like this:
// 1. Visit the 3rd party site (http://auth.corp.com:7075) and tell
// the 3rd party site where to redirect back to upon success:
// http://auth.corp.com:7075?redirectTo=http://localhost:7074/set_token
// 2. Submit the username / password to the auth.corp.com site
// 3. Upon success, the 3rd party site redirects back to your application
// and includes the id_token in the URL:
// http://localhost:7074/set_token?id_token=abc123def456
// 4. Your application then parses out the id_token and sets it
// as a cookie or on local storage then includes it on all
// subsequent requests to your server.
// There are other various implementation differences but they all share
// the same fundamental concepts which we can test in Cypress.
const _ = Cypress._
// require node's url module
const url = require('url')
describe('Logging In - Single Sign on', function () {
Cypress.Commands.add('loginBySingleSignOn', (overrides = {}) => {
Cypress.log({
name: 'loginBySingleSignOn',
})
const options = {
method: 'POST',
url: 'http://auth.corp.com:7075/login',
qs: {
// use qs to set query string to the url that creates
// http://auth.corp.com:8080?redirectTo=http://localhost:7074/set_token
redirectTo: 'http://localhost:7074/set_token',
},
form: true, // we are submitting a regular form body
body: {
username: 'jane.lane',
password: 'password123',
},
}
// allow us to override defaults with passed in overrides
_.extend(options, overrides)
cy.request(options)
})
context('Use redirectTo and a session cookie to login', function () {
// This first example assumes we have an app server that
// is capable of handling the redirect and set a session cookie
// The flow will be:
// 1. sign into auth.corp.com
// 2. redirect back to our app server
// 3. have our app server set an HttpOnly session cookie
// 4. check that we are now properly logged in
it('is 403 unauthorized without a session cookie', function () {
// smoke test just to show that without logging in we cannot
// visit the dashboard
cy.visit('/dashboard')
cy.get('h3').should(
'contain',
'You are not logged in and cannot access this page'
)
cy.url().should('include', 'unauthorized')
})
it('can authenticate with cy.request', function () {
// before we start, there should be no session cookie
cy.getCookie('cypress-session-cookie').should('not.exist')
// this automatically gets + sets cookies on the browser
// and follows all of the redirects that ultimately get
// us to /dashboard.html
cy.loginBySingleSignOn().then((resp) => {
// yup this should all be good
expect(resp.status).to.eq(200)
// we're at http://localhost:7074/dashboard contents
expect(resp.body).to.include('<h1>Welcome to the Dashboard!</h1>')
})
// the redirected page hits the server, and the server middleware
// parses the authentication token and returns the dashboard view
// with our cookie 'cypress-session-cookie' set
cy.getCookie('cypress-session-cookie').should('exist')
// you don't need to do this next part but
// just to prove we can also visit the page in our app
cy.visit('/dashboard')
cy.get('h1').should('contain', 'Welcome to the Dashboard')
})
})
context(
'Manually parse id_token and set on local storage to login',
function () {
// This second example assumes we are building a SPA
// without a server to handle setting the session cookie.
// The flow will be:
// 1. Disable following automatic redirects
// 2. Sign into auth.corp.com
// 3. Parse out the id_token manually
// 4. Visit our application
// 5. Before it loads, set token on local storage
// 6. Make sure the XHR goes out and the response
// is correct + #main has the correct response text
it('knows when there is no session token', function () {
// by default our SPA app checks for id_token set in local storage
// and will display a message if its not set
//
// else it will make an XHR request to the backend and display the results
cy.visit('/')
cy.get('#main').should('contain', 'No session token set!')
})
/**
* Assuming "cy.request" was called with `{followRedirect: false}` grabs the
* redirected to URI, parses it and returns just the "id_token".
*/
const responseToToken = (resp) => {
// we can use the redirectedToUrl property that Cypress adds
// whenever we turn off following redirects
//
// and use node's url.parse module (and parse the query params)
const uri = url.parse(resp.redirectedToUrl, true)
// we now have query params as an object and can return
// the id_token
expect(uri.query).to.have.property('id_token')
return uri.query.id_token
}
it('can parse out id_token and set on local storage', function () {
// dont follow redirects so we can manually parse out the id_token
cy.loginBySingleSignOn({ followRedirect: false })
.then(responseToToken)
.then((id_token) => {
// observe the "GET /config" call from the application
cy.intercept('/config').as('getConfig')
// now go visit our app
cy.visit('/', {
onBeforeLoad (win) {
// and before the page finishes loading
// set the id_token in local storage
win.localStorage.setItem('id_token', id_token)
},
})
// wait for the /config XHR
cy.wait('@getConfig')
.its('response.body')
.should('deep.eq', {
foo: 'bar',
some: 'config',
loggedIn: true,
})
// and now our #main should be filled
// with the response body
cy.get('#main')
.invoke('text')
.should((text) => {
// parse the text into JSON
const json = JSON.parse(text)
expect(json).to.deep.eq({
foo: 'bar',
some: 'config',
loggedIn: true,
})
})
})
})
describe('Log in once for speed', () => {
// in this example we follow SPA workflow, get the auth token once
// and then set it in window.localStorage before each test
// and voilá - we are logged in very quickly
before(function () {
// before any tests execute, get the token once
// as save it in the test context - thus the callback
// is using "function () { ... }" form and NOT arrow function
cy.loginBySingleSignOn({ followRedirect: false })
.then(responseToToken)
.as('token') // saves under "this.token"
})
beforeEach(function () {
// before every test we need to grab "this.token"
// and set it in the local storage,
// so the application sends with and the user is authenticated
cy.on('window:before:load', (win) => {
win.localStorage.setItem('id_token', this.token)
})
})
it('opens page as logged in user', () => {
cy.visit('/')
cy.contains('"loggedIn":true')
})
it('config returns logged in: true', function () {
// note again this test uses "function () { ... }" callback
// in order to get access to the test context "this.token" saved above
// observe the "GET /config" call from the application
cy.intercept('/config', (req) => {
// a work around to prevent cached results
delete req.headers['if-none-match']
}).as('getConfig')
cy.visit('/')
cy.wait('@getConfig').then((xhr) => {
// inspect sent and received information
expect(
xhr.request.headers,
'request includes token header'
).to.have.property('x-session-token', this.token)
expect(xhr.response.body, 'response body').to.deep.equal({
foo: 'bar',
loggedIn: true,
some: 'config',
})
})
})
})
}
)
})