-
Notifications
You must be signed in to change notification settings - Fork 926
/
Copy pathoauth2.ts
399 lines (332 loc) · 11.7 KB
/
oauth2.ts
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import { nanoid } from 'nanoid'
import requrl from 'requrl'
import { encodeQuery, getResponseProp, normalizePath, parseQuery, removeTokenPrefix, urlJoin } from '../utils'
import RefreshController from '../inc/refresh-controller'
import RequestHandler from '../inc/request-handler'
import ExpiredAuthSessionError from '../inc/expired-auth-session-error'
import Token from '../inc/token'
import RefreshToken from '../inc/refresh-token'
import type { SchemeCheck } from '../index'
import BaseScheme from './_scheme'
const DEFAULTS = {
name: 'oauth2',
accessType: null,
redirectUri: null,
logoutRedirectUri: null,
clientId: null,
audience: null,
grantType: null,
responseMode: null,
acrValues: null,
autoLogout: false,
endpoints: {
logout: '',
authorization: '',
token: '',
userInfo: ''
},
scope: [],
token: {
property: 'access_token',
type: 'Bearer',
name: 'Authorization',
maxAge: 1800,
global: true,
prefix: '_token.',
expirationPrefix: '_token_expiration.'
},
refreshToken: {
property: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
prefix: '_refresh_token.',
expirationPrefix: '_refresh_token_expiration.'
},
user: {
property: false
},
responseType: 'token',
codeChallengeMethod: 'implicit'
}
export default class Oauth2Scheme extends BaseScheme<typeof DEFAULTS> {
public req
public token: Token
public refreshToken: RefreshToken
public refreshController: RefreshController
public requestHandler: RequestHandler
constructor ($auth, options, ...defaults) {
super($auth, options, ...defaults, DEFAULTS)
this.req = $auth.ctx.req
// Initialize Token instance
this.token = new Token(this, this.$auth.$storage)
// Initialize Refresh Token instance
this.refreshToken = new RefreshToken(this, this.$auth.$storage)
// Initialize Refresh Controller
this.refreshController = new RefreshController(this)
// Initialize Request Handler
this.requestHandler = new RequestHandler(this, this.$auth.ctx.$axios)
}
get _scope () {
return Array.isArray(this.options.scope)
? this.options.scope.join(' ')
: this.options.scope
}
get _redirectURI () {
return this.options.redirectUri || urlJoin(requrl(this.req), this.$auth.options.redirect.callback)
}
get _logoutRedirectURI () {
return this.options.logoutRedirectUri || urlJoin(requrl(this.req), this.$auth.options.redirect.logout)
}
_updateTokens (response) {
const token = getResponseProp(response, this.options.token.property)
const refreshToken = getResponseProp(response, this.options.refreshToken.property)
this.token.set(token)
if (refreshToken) {
this.refreshToken.set(refreshToken)
}
}
check (checkStatus = false): SchemeCheck {
const response = {
valid: false,
tokenExpired: false,
refreshTokenExpired: false,
isRefreshable: true
}
// Sync tokens
const token = this.token.sync()
this.refreshToken.sync()
// Token is required but not available
if (!token) {
return response
}
// Check status wasn't enabled, let it pass
if (!checkStatus) {
response.valid = true
return response
}
// Get status
const tokenStatus = this.token.status()
const refreshTokenStatus = this.refreshToken.status()
// Refresh token has expired. There is no way to refresh. Force reset.
if (refreshTokenStatus.expired()) {
response.refreshTokenExpired = true
return response
}
// Token has expired, Force reset.
if (tokenStatus.expired()) {
response.tokenExpired = true
return response
}
response.valid = true
return response
}
async mounted () {
const { tokenExpired, refreshTokenExpired } = this.check(true)
// Force reset if refresh token has expired
// Or if `autoLogout` is enabled and token has expired
if (refreshTokenExpired || (tokenExpired && this.options.autoLogout)) {
this.$auth.reset()
}
// Initialize request interceptor
this.requestHandler.initializeRequestInterceptor(this.options.endpoints.token)
// Handle callbacks on page load
const redirected = await this._handleCallback()
if (!redirected) {
return this.$auth.fetchUserOnce()
}
}
reset () {
this.$auth.setUser(false)
this.token.reset()
this.refreshToken.reset()
this.requestHandler.reset()
}
_generateRandomString () {
const array = new Uint32Array(28) // this is of minimum required length for servers with PKCE-enabled
window.crypto.getRandomValues(array)
return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('')
}
_sha256 (plain) {
const encoder = new TextEncoder()
const data = encoder.encode(plain)
return window.crypto.subtle.digest('SHA-256', data)
}
_base64UrlEncode (str) {
// Convert the ArrayBuffer to string using Uint8 array to convert to what btoa accepts.
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
// Then convert the base64 encoded to base64url encoded
// (replace + with -, replace / with _, trim trailing =)
return btoa(String.fromCharCode.apply(null, new Uint8Array(str)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
async _pkceChallengeFromVerifier (v, hashValue) {
if (hashValue) {
const hashed = await this._sha256(v)
return this._base64UrlEncode(hashed)
}
return v // plain is plain - url-encoded by default
}
async login (_opts: { state?, params?, nonce? } = {}) {
const opts = {
protocol: 'oauth2',
response_type: this.options.responseType,
access_type: this.options.accessType,
client_id: this.options.clientId,
redirect_uri: this._redirectURI,
scope: this._scope,
// Note: The primary reason for using the state parameter is to mitigate CSRF attacks.
// https://auth0.com/docs/protocols/oauth2/oauth-state
state: _opts.state || nanoid(),
code_challenge_method: this.options.codeChallengeMethod,
..._opts.params
}
if (this.options.audience) {
opts.audience = this.options.audience
}
// Set Nonce Value if response_type contains id_token to mitigate Replay Attacks
// More Info: https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes
// More Info: https://tools.ietf.org/html/draft-ietf-oauth-v2-threatmodel-06#section-4.6.2
if (opts.response_type.includes('id_token')) {
// nanoid auto-generates an URL Friendly, unique Cryptographic string
// Recommended by Auth0 on https://auth0.com/docs/api-auth/tutorials/nonce
opts.nonce = _opts.nonce || nanoid()
}
if (opts.code_challenge_method) {
switch (opts.code_challenge_method) {
case 'plain':
case 'S256': {
const state = this._generateRandomString()
this.$auth.$storage.setUniversal(this.name + '.pkce_state', state)
const codeVerifier = this._generateRandomString()
this.$auth.$storage.setUniversal(this.name + '.pkce_code_verifier', codeVerifier)
const codeChallenge = await this._pkceChallengeFromVerifier(codeVerifier, opts.code_challenge_method === 'S256')
opts.code_challenge = window.encodeURIComponent(codeChallenge)
}
break
case 'implicit':
default:
break
}
}
if (this.options.responseMode) {
opts.response_mode = this.options.responseMode
}
if (this.options.acrValues) {
opts.acr_values = this.options.acrValues
}
this.$auth.$storage.setUniversal(this.name + '.state', opts.state)
const url = this.options.endpoints.authorization + '?' + encodeQuery(opts)
window.location.replace(url)
}
logout () {
if (this.options.endpoints.logout) {
const opts = {
client_id: this.options.clientId,
logout_uri: this._logoutRedirectURI
}
const url = this.options.endpoints.logout + '?' + encodeQuery(opts)
window.location.replace(url)
}
return this.$auth.reset()
}
async fetchUser () {
if (!this.check().valid) {
return
}
if (!this.options.endpoints.userInfo) {
this.$auth.setUser({})
return
}
const response = await this.$auth.requestWith(this.name, {
url: this.options.endpoints.userInfo
})
this.$auth.setUser(getResponseProp(response, this.options.user.property))
}
async _handleCallback () {
// Handle callback only for specified route
if (this.$auth.options.redirect && normalizePath(this.$auth.ctx.route.path) !== normalizePath(this.$auth.options.redirect.callback)) {
return
}
// Callback flow is not supported in server side
if (process.server) {
return
}
const hash = parseQuery(this.$auth.ctx.route.hash.substr(1))
const parsedQuery = Object.assign({}, this.$auth.ctx.route.query, hash)
// accessToken/idToken
let token = parsedQuery[this.options.token.property]
// refresh token
let refreshToken = parsedQuery[this.options.refreshToken.property]
// Validate state
const state = this.$auth.$storage.getUniversal(this.name + '.state')
this.$auth.$storage.setUniversal(this.name + '.state', null)
if (state && parsedQuery.state !== state) {
return
}
// -- Authorization Code Grant --
if (this.options.responseType === 'code' && parsedQuery.code) {
let codeVerifier
// Retrieve code verifier and remove it from storage
if (this.options.codeChallengeMethod && this.options.codeChallengeMethod !== 'implicit') {
codeVerifier = this.$auth.$storage.getUniversal(this.name + '.pkce_code_verifier')
this.$auth.$storage.setUniversal(this.name + '.pkce_code_verifier', null)
}
const response = await this.$auth.request({
method: 'post',
url: this.options.endpoints.token,
baseURL: '',
data: encodeQuery({
code: parsedQuery.code,
client_id: this.options.clientId,
redirect_uri: this._redirectURI,
response_type: this.options.responseType,
audience: this.options.audience,
grant_type: this.options.grantType,
code_verifier: codeVerifier
})
})
token = getResponseProp(response, this.options.token.property) || token
refreshToken = getResponseProp(response, this.options.refreshToken.property) || refreshToken
}
if (!token || !token.length) {
return
}
// Set token
this.token.set(token)
// Store refresh token
if (refreshToken && refreshToken.length) {
this.refreshToken.set(refreshToken)
}
// Redirect to home
this.$auth.redirect('home', true)
return true // True means a redirect happened
}
async refreshTokens () {
// Get refresh token
const refreshToken = this.refreshToken.get()
// Refresh token is required but not available
if (!refreshToken) { return }
// Get refresh token status
const refreshTokenStatus = this.refreshToken.status()
// Refresh token is expired. There is no way to refresh. Force reset.
if (refreshTokenStatus.expired()) {
this.$auth.reset()
throw new ExpiredAuthSessionError()
}
// Delete current token from the request header before refreshing
this.requestHandler.clearHeader()
const response = await this.$auth.request({
method: 'post',
url: this.options.endpoints.token,
data: encodeQuery({
refresh_token: removeTokenPrefix(refreshToken, this.options.token.type),
client_id: this.options.clientId,
grant_type: 'refresh_token'
})
}).catch((error) => {
this.$auth.callOnError(error, { method: 'refreshToken' })
return Promise.reject(error)
})
this._updateTokens(response)
return response
}
}