-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAuthCodeProvider.tsx
657 lines (593 loc) · 19 KB
/
AuthCodeProvider.tsx
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import * as React from 'react'
import PropTypes from 'prop-types'
import Cookies from 'universal-cookie'
import axios from 'axios'
import * as AuthCodeFunctions from './AuthCodeFunctions'
// eslint-disable-next-line no-unused-vars
import AuthCodeProps from './AuthCodeProps'
import Loader from './AuthCodeLoader'
import Message from './AuthCodeMessage'
const cookies = new Cookies()
const qs = require('querystring')
interface IAuthCodeProviderProps {
children?: any
authenticationRequired?: boolean
doLogout?: boolean
authenticationProps: AuthCodeProps
returnTo?: string
history: any
storagePrefix: string
cookiePath: string
onGetAuthCode?: () => void
onReceiveAuthCode?: (authcode: string) => void
onTokenObtained?: (data: any) => void
onTokenObtainedError?: (error: Error) => void
onTokenRefreshed?: (data: any) => void
onTokenRefreshedError?: (error: Error) => void
enableDebugLog?: boolean
signInText: string
signOutText: string
signInErrorText: string
refreshErrorText: string
loaderComponent?: (props: any) => JSX.Element
signInErrorComponent?: (props: any) => JSX.Element
}
interface IAuthCodeProviderState {
loading: boolean
signinError: boolean
}
const initialState: IAuthCodeProviderState = {
loading: true,
signinError: false
}
class AuthCodeProvider extends React.Component<
IAuthCodeProviderProps,
IAuthCodeProviderState
> {
static defaultProps = {
authenticationRequired: true,
doLogout: false,
storagePrefix: '',
cookiePath: '/',
enableDebugLog: false,
signInText: 'Signing you in...',
signOutText: 'Signing you out...',
signInErrorText:
'Sorry, we were unable to sign you in. Please try again later.',
refreshErrorText: 'Your session has expired.\nSign in again to continue.'
}
static propTypes = {
/**
* A prop used to toggle whether authentication is required.
* If false children will be rendered.
* If true, children will only be rendered when authenticated.
* Changing from false to true can be used to start the authentication flow.
*/
authenticationRequired: PropTypes.bool,
/**
* A prop used to begin the logout flow.
* Changing from false to true can be used to start the logout flow.
*/
doLogout: PropTypes.bool,
/**
* An instance of the AuthCodeAuthentication class. This contains properties needed to for the authentication flow.
*/
authenticationProps: PropTypes.object.isRequired,
/**
* Once a token has been retrieved this is the path to redirect back to. If not set it will redirect back to the current path.
*/
returnTo: PropTypes.string,
/**
* React router history object. If set this will be used for post authentication redirects and removing the code parameter.
* If not provided the page will be reloaded to remove the code parameter and redirect.
*/
history: PropTypes.any,
/**
* Used if you are aythenticating with multiple oauth2 servers, you can store multiple access tokens.
* The second/third/etc instance should have a unique prefixes.
*/
storagePrefix: PropTypes.string,
/**
* Determines the Path for cookies. If hosting in a subdirectory you should set this to the subdirectory path (/subdriectory)
*/
cookiePath: PropTypes.string,
/**
* A call back function that is called before being redirecting to the authorization endpoint.
*/
onGetAuthCode: PropTypes.func,
/**
* A call back function that is called when redirected back to the application with the Code parameter populated.
*/
onReceiveAuthCode: PropTypes.func,
/**
* A call back function that is called after retrieving an access token.
*/
onTokenObtained: PropTypes.func,
/**
* A call back function that is called if there is an error retrieving an access token.
*/
onTokenObtainedError: PropTypes.func,
/**
* A call back function that is called after retrieving an access token from a refresh token in the background.
*/
onTokenRefreshed: PropTypes.func,
/**
* A call back function that is called if there is an error retrieving access token from a refresh token in the background.
*/
onTokenRefreshedError: PropTypes.func,
/**
* Set to true to allow addiitonal logging to the console
*/
enableDebugLog: PropTypes.bool,
/**
* The label 'Signing you in'
*/
signInText: PropTypes.string,
/**
* The label 'Signing you out'
*/
signOutText: PropTypes.string,
/**
* The label 'Sorry, we were unable to sign you in. Please try again later.'
*/
signInErrorText: PropTypes.string,
/**
* The label 'Your session has expired.\nSign in again to continue.'
*/
refreshErrorText: PropTypes.string,
/**
* You can use this prop to override the Loader with your own component.
* The component must support the props: text<string>.
*/
loaderComponent: PropTypes.any,
/**
* You can use this prop to override the Sign in error message with your own component.
* The component must support the props: text<string>, btnText<string>, onBtnClick<function>.
*/
signInErrorComponent: PropTypes.any
}
refreshTimer: any
constructor(props: IAuthCodeProviderProps) {
super(props)
this.state = initialState
this.retryAuth = this.retryAuth.bind(this)
}
componentDidMount() {
if (this.props.doLogout) {
this.doLogout()
} else {
this.processAuth(false)
}
}
componentDidUpdate(prevProps: IAuthCodeProviderProps): void {
if (this.props.doLogout && !prevProps.doLogout) {
this.doLogout()
} else if (
this.props.authenticationRequired &&
!prevProps.authenticationRequired
) {
this.processAuth(false)
}
}
componentWillUnmount() {
// Clean up
if (this.refreshTimer) {
clearInterval(this.refreshTimer)
this.refreshTimer = null
}
}
/**
* Checks to see if any action is required to authenticate, and iniates it if neccessary.
*/
private processAuth(isRefresh: boolean): void {
this.debugit('Authentication Required')
let tokenExpired: boolean = false
const accessTokenExpiry: any = localStorage.getItem(
this.props.storagePrefix + 'access_token_expiry'
)
if (accessTokenExpiry) {
var now = new Date()
const accessTokenExpiryDate = new Date(accessTokenExpiry)
if (now >= accessTokenExpiryDate) {
tokenExpired = true
} else {
const diffMs = accessTokenExpiryDate.valueOf() - now.valueOf()
this.setTokenRefresh(diffMs)
}
}
if (
AuthCodeFunctions.hasAccessToken(this.props.storagePrefix) &&
!tokenExpired
) {
// We have an access token already, no need to do anything
this.debugit(
'Access token present and valid. Expiry = ' + accessTokenExpiry
)
if (this.state.loading) {
this.setState({ loading: false })
}
} else if (AuthCodeFunctions.hasRefreshToken(this.props.storagePrefix)) {
// We have a refresh token but no access token, use this to get a new access token
this.debugit('Refresh token present. Feteching new access token')
this.doRefreshFlow(isRefresh)
} else if (isRefresh) {
// Encountered an issue - display error
this.sessionExpired()
} else {
const code = AuthCodeFunctions.getURIParameterByName(
'code',
window.location.href
)
if (code) {
// We have an authentication code, trade for token
this.debugit('Authentication code detected. Fetching token')
if (this.props.onReceiveAuthCode != null) {
this.props.onReceiveAuthCode(code)
}
this.tradeCodeForToken(code)
} else if (this.props.authenticationRequired) {
// We have nothing, time to get a code
this.debugit('Redirecting to authoisation endpoint')
this.getAuthCode()
} else {
// authentication not required
this.setState({ loading: false })
}
}
}
/**
* Iniates the logout flow
*/
private doLogout(): void {
AuthCodeFunctions.doLogoutFlow(
this.props.authenticationProps,
this.props.storagePrefix
)
}
/**
* Sets up redirect to the authorization endpoint
* @param isretry set to true if this is the second/third/nth attempt after an error with the first
*/
private getAuthCode(isretry: boolean = false): void {
if (this.props.onGetAuthCode != null) {
this.props.onGetAuthCode()
}
this.setState({ loading: true })
AuthCodeFunctions.doAuthorizationCodeFlow(
this.props.authenticationProps,
this.props.returnTo,
this.props.storagePrefix,
isretry
)
}
/**
* Trade the Code in the uri for a token using by doing a post to the token endpoint
* @param code the code from the code query string parameter
*/
private tradeCodeForToken(code: string): void {
const {
tokenUrl,
callBackPath,
clientId,
clientSecret,
scope,
usePkce,
useState
} = this.props.authenticationProps
this.debugit('Code url: ' + window.location.href)
if (useState) {
const codeState = AuthCodeFunctions.getURIParameterByName(
'state',
window.location.href
)
const origState = localStorage.getItem(
this.props.storagePrefix + 'authcode_state'
)
if (codeState !== origState) {
const stateErr = 'State does not match'
this.debugit(stateErr)
console.log(stateErr)
if (this.props.onTokenObtainedError != null) {
this.props.onTokenObtainedError(new Error(stateErr))
}
this.setState({ signinError: true })
} else {
this.debugit('State matches ' + origState)
}
localStorage.removeItem(this.props.storagePrefix + 'authcode_state')
}
const params: any = {
grant_type: 'authorization_code',
client_id: clientId,
redirect_uri: AuthCodeFunctions.buildRedirectUri(callBackPath),
scope: scope,
code: code
}
if (clientSecret) {
params.client_secret = clientSecret
}
if (scope) {
params.scope = scope
}
if (usePkce) {
const verifier = localStorage.getItem(
this.props.storagePrefix + 'authcode_v'
)
if (verifier) {
params.code_verifier = verifier
}
}
axios
.post(tokenUrl, qs.stringify(params), {
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
.then((response: any) => {
this.debugit('Access token response')
this.debugit(response)
if (!response.data || !response.data.access_token) {
throw new Error('Access token not present in token response')
}
if (response.data.error) {
throw new Error(response.data.error_description)
}
this.setTokens(response.data, false)
if (this.props.onTokenObtained != null) {
this.props.onTokenObtained(response.data)
}
})
.catch((error: any) => {
console.log(error)
this.debugit('Access token error')
this.debugit(error?.response)
if (this.props.onTokenObtainedError != null) {
this.props.onTokenObtainedError(error)
}
this.setState({ signinError: true })
})
}
/**
* Use the refresh token to obtain a new access token. Does a post to the token endpoints
* @param isRefresh if this is happening in the background (not initial fetch)
*/
private doRefreshFlow(isRefresh: boolean): void {
const {
tokenUrl,
callBackPath,
clientId,
clientSecret,
scope
} = this.props.authenticationProps
const params: any = {
grant_type: 'refresh_token',
client_id: clientId,
redirect_uri: AuthCodeFunctions.buildRedirectUri(callBackPath),
scope: scope,
refresh_token: AuthCodeFunctions.refreshToken(this.props.storagePrefix)
}
if (clientSecret) {
params.client_secret = clientSecret
}
if (scope) {
params.scope = scope
}
axios
.post(tokenUrl, qs.stringify(params), {
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
.then((response: any) => {
this.debugit('Refresh token response')
this.debugit(response)
if (!response.data || !response.data.access_token) {
throw new Error('Access token not present in token response')
}
if (response.data.error) {
throw new Error(response.data.error_description)
}
this.setTokens(response.data, true)
if (!isRefresh) {
if (this.props.onTokenObtained != null) {
this.props.onTokenObtained(response.data)
}
} else {
if (this.props.onTokenRefreshed != null) {
this.props.onTokenRefreshed(response.data)
}
}
})
.catch((error: any) => {
console.log(error)
this.debugit('Refresh token error')
this.debugit(error?.response)
if (!isRefresh) {
if (this.props.authenticationRequired) {
this.setState({ signinError: true })
} else {
this.setState({ loading: false })
cookies.remove(this.props.storagePrefix + 'refresh_token')
localStorage.removeItem(this.props.storagePrefix + 'id_token')
}
if (this.props.onTokenObtainedError != null) {
this.props.onTokenObtainedError(error)
}
} else {
if (this.props.onTokenRefreshedError != null) {
this.props.onTokenRefreshedError(error)
}
}
})
}
/**
* If token expires mid session, or refresh fails mid session, this is called to get the user to take action to re-authorize.
*/
private sessionExpired(): void {
var expiredresult = window.confirm(this.props.refreshErrorText)
if (expiredresult) {
this.retryAuth()
} else {
setTimeout(this.processAuth.bind(this, true), 60000)
}
}
/**
* Handles token endpoint response and saves tokens
* @param response response from the token endpoint
* @param isrefresh if this is happening in the background (not initial fetch)
*/
private setTokens(response: any, isrefresh: boolean): void {
// save id token in storage and check nonce
const idToken = response.id_token
if (idToken) {
const origNonce = localStorage.getItem(
this.props.storagePrefix + 'authcode_nonce'
)
if (this.props.authenticationProps.useNonce && origNonce) {
const idTokenObj = JSON.parse(AuthCodeFunctions.parseJwt(idToken))
if (idTokenObj) {
if (idTokenObj.nonce !== origNonce) {
console.log(idTokenObj)
this.debugit('Expected nonce ' + origNonce)
this.debugit('Actual nonce ' + idTokenObj.nonce)
throw new Error('Nonce does not match')
} else {
this.debugit('Nonce matches ' + origNonce)
}
}
}
if (origNonce) {
localStorage.removeItem(this.props.storagePrefix + 'authcode_nonce')
}
localStorage.setItem(this.props.storagePrefix + 'id_token', idToken)
}
let expiryMins = 60
if (response.expires_in) {
expiryMins = response.expires_in / 60
}
// We remove 2 minutes from the expiry to give a buffer for refresh
expiryMins = expiryMins - 2
if (expiryMins < 1) {
expiryMins = 1
}
this.debugit('Token expiry mins: ' + expiryMins)
const now = new Date()
const expiryDate = new Date(now.getTime() + expiryMins * 60000)
localStorage.setItem(
this.props.storagePrefix + 'access_token_expiry',
expiryDate.toString()
)
cookies.set(
this.props.storagePrefix + 'access_token',
response.access_token,
{ path: this.props.cookiePath }
)
this.debugit('New Access Token: ' + response.access_token)
// update refresh token cookie
let refreshToken = response.refresh_token
if (!refreshToken) {
refreshToken = AuthCodeFunctions.refreshToken(this.props.storagePrefix)
}
if (refreshToken) {
cookies.set(this.props.storagePrefix + 'refresh_token', refreshToken, {
path: this.props.cookiePath,
expires: new Date(now.setMonth(now.getMonth() + 4))
})
this.debugit('New Refresh Token: ' + response.access_token)
}
this.setTokenRefresh(1 * 60 * 1000)
if (!isrefresh) {
// Remove Verifier
const verifier = localStorage.getItem(
this.props.storagePrefix + 'authcode_v'
)
if (verifier) {
localStorage.removeItem(this.props.storagePrefix + 'authcode_v')
}
// Redirect if set
let redirectpath = localStorage.getItem(
this.props.storagePrefix + 'authcode_authentication_redirect'
)
if (!redirectpath) {
redirectpath = ''
} else {
localStorage.removeItem(
this.props.storagePrefix + 'authcode_authentication_redirect'
)
}
if (this.props.history) {
this.props.history.replace({
pathname: redirectpath.includes('?')
? redirectpath.substring(0, redirectpath.indexOf('?'))
: redirectpath,
search: redirectpath.includes('?')
? redirectpath.substring(redirectpath.indexOf('?'))
: ''
})
} else {
window.location.replace(redirectpath)
}
}
if (this.state.loading) {
this.setState({ loading: false })
}
}
/**
* Does a set timeout to allow a refresh when the token expires
* @param expiryMilliSecs Milliseconds until token expiry minus 2 mins
*/
private setTokenRefresh(expiryMilliSecs: number) {
// Set up refresh interval
if (this.refreshTimer) {
clearInterval(this.refreshTimer)
this.refreshTimer = null
}
this.refreshTimer = setTimeout(
this.processAuth.bind(this, true),
expiryMilliSecs
)
}
/**
* Retry the authorization if it has failed
*/
private retryAuth(): void {
cookies.remove(this.props.storagePrefix + 'access_token')
cookies.remove(this.props.storagePrefix + 'refresh_token')
localStorage.removeItem(this.props.storagePrefix + 'id_token')
this.getAuthCode(true)
}
/**
* Log additional information
* @param line what to log
*/
private debugit(line: string): void {
if (this.props.enableDebugLog) {
console.log(line)
}
}
render() {
if (this.state.signinError) {
return React.createElement(
this.props.signInErrorComponent
? this.props.signInErrorComponent
: Message,
{
text: this.props.signInErrorText,
btnText: 'Retry',
onBtnClick: this.retryAuth
}
)
}
if (this.state.loading || this.props.doLogout) {
const loadertext = this.props.doLogout
? this.props.signOutText
: this.props.signInText
return React.createElement(
this.props.loaderComponent ? this.props.loaderComponent : Loader,
{ text: loadertext }
)
}
return this.props.children
}
}
export default AuthCodeProvider