-
Notifications
You must be signed in to change notification settings - Fork 925
/
Copy pathoauth2.ts
525 lines (455 loc) · 14 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import requrl from 'requrl'
import type {
RefreshableScheme,
SchemePartialOptions,
SchemeCheck,
RefreshableSchemeOptions,
UserOptions,
SchemeOptions,
HTTPResponse,
EndpointsOption,
TokenableSchemeOptions
} from '../types'
import type { Auth } from '../core'
import {
encodeQuery,
getProp,
normalizePath,
parseQuery,
removeTokenPrefix,
urlJoin,
randomString
} from '../utils'
import {
RefreshController,
RequestHandler,
ExpiredAuthSessionError,
Token,
RefreshToken
} from '../inc'
import { BaseScheme } from './base'
export interface Oauth2SchemeEndpoints extends EndpointsOption {
authorization: string
token: string
userInfo: string
logout: string | false
}
export interface Oauth2SchemeOptions
extends SchemeOptions,
TokenableSchemeOptions,
RefreshableSchemeOptions {
endpoints: Oauth2SchemeEndpoints
user: UserOptions
responseMode: 'query.jwt' | 'fragment.jwt' | 'form_post.jwt' | 'jwt'
responseType: 'code' | 'token' | 'id_token' | 'none' | string
grantType:
| 'implicit'
| 'authorization_code'
| 'client_credentials'
| 'password'
| 'refresh_token'
| 'urn:ietf:params:oauth:grant-type:device_code'
accessType: 'online' | 'offline'
redirectUri: string
logoutRedirectUri: string
clientId: string | number
scope: string | string[]
state: string
codeChallengeMethod: 'implicit' | 'S256' | 'plain' | ''
acrValues: string
audience: string
autoLogout: boolean
}
const DEFAULTS: SchemePartialOptions<Oauth2SchemeOptions> = {
name: 'oauth2',
accessType: null,
redirectUri: null,
logoutRedirectUri: null,
clientId: null,
audience: null,
grantType: null,
responseMode: null,
acrValues: null,
autoLogout: false,
endpoints: {
logout: null,
authorization: null,
token: null,
userInfo: null
},
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 class Oauth2Scheme<
OptionsT extends Oauth2SchemeOptions = Oauth2SchemeOptions
>
extends BaseScheme<OptionsT>
implements RefreshableScheme
{
public req
public token: Token
public refreshToken: RefreshToken
public refreshController: RefreshController
public requestHandler: RequestHandler
constructor(
$auth: Auth,
options: SchemePartialOptions<Oauth2SchemeOptions>,
...defaults: SchemePartialOptions<Oauth2SchemeOptions>[]
) {
super(
$auth,
options as OptionsT,
...(defaults as OptionsT[]),
DEFAULTS as OptionsT
)
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)
}
protected get scope(): string {
return Array.isArray(this.options.scope)
? this.options.scope.join(' ')
: this.options.scope
}
protected get redirectURI(): string {
const basePath = this.$auth.ctx.base || ''
const path = normalizePath(
basePath + '/' + this.$auth.options.redirect.callback
) // Don't pass in context since we want the base path
return this.options.redirectUri || urlJoin(requrl(this.req), path)
}
protected get logoutRedirectURI(): string {
return (
this.options.logoutRedirectUri ||
urlJoin(requrl(this.req), this.$auth.options.redirect.logout)
)
}
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(): Promise<HTTPResponse | void> {
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(): void {
this.$auth.setUser(false)
this.token.reset()
this.refreshToken.reset()
this.requestHandler.reset()
}
async login(
_opts: { state?: string; params?; nonce?: string } = {}
): Promise<void> {
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 || randomString(10),
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')) {
opts.nonce = _opts.nonce || randomString(10)
}
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(): void {
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(): Promise<void> {
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(getProp(response.data, this.options.user.property))
}
async _handleCallback(): Promise<boolean | void> {
// Handle callback only for specified route
if (
this.$auth.options.redirect &&
normalizePath(this.$auth.ctx.route.path, this.$auth.ctx) !==
normalizePath(this.$auth.options.redirect.callback, this.$auth.ctx)
) {
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: string = parsedQuery[this.options.token.property] as string
// refresh token
let refreshToken: string
if (this.options.refreshToken.property) {
refreshToken = parsedQuery[this.options.refreshToken.property] as string
}
// 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 as string,
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 =
(getProp(response.data, this.options.token.property) as string) || token
refreshToken =
(getProp(
response.data,
this.options.refreshToken.property
) as string) || 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(): Promise<HTTPResponse | void> {
// 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,
baseURL: '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
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
}
protected updateTokens(response: HTTPResponse): void {
const token = getProp(response.data, this.options.token.property) as string
const refreshToken = getProp(
response.data,
this.options.refreshToken.property
) as string
this.token.set(token)
if (refreshToken) {
this.refreshToken.set(refreshToken)
}
}
protected async pkceChallengeFromVerifier(
v: string,
hashValue: boolean
): Promise<string> {
if (hashValue) {
const hashed = await this._sha256(v)
return this._base64UrlEncode(hashed)
}
return v // plain is plain - url-encoded by default
}
protected generateRandomString(): string {
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(
''
)
}
private _sha256(plain: string): Promise<ArrayBuffer> {
const encoder = new TextEncoder()
const data = encoder.encode(plain)
return window.crypto.subtle.digest('SHA-256', data)
}
private _base64UrlEncode(str: ArrayBuffer): string {
// 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(/=+$/, '')
}
}