Skip to content
This repository was archived by the owner on Jun 15, 2023. It is now read-only.

Commit 7f72ec5

Browse files
committed
Adding jwt-decode
1 parent 4d9dd6e commit 7f72ec5

7 files changed

Lines changed: 659 additions & 595 deletions

File tree

example/package-lock.json

Lines changed: 610 additions & 568 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/src/App.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import { AuthProvider, AuthService } from 'react-oauth2-pkce'
44
import { Routes } from './Routes';
55

66
const authService = new AuthService({
7-
clientId: process.env.REACT_APP_CLIENT_ID || 'CHANGEME',
8-
location: window.location,
9-
provider: process.env.REACT_APP_PROVIDER || 'https://sandbox.auth.ap-southeast-2.amazoncognito.com/oauth2',
10-
redirectUri: process.env.REACT_APP_REDIRECT_URI || window.location.origin,
11-
scopes: ['openid', 'profile']
7+
clientId: process.env.REACT_APP_CLIENT_ID || 'CHANGEME',
8+
location: window.location,
9+
provider: process.env.REACT_APP_PROVIDER || 'https://sandbox.auth.ap-southeast-2.amazoncognito.com/oauth2',
10+
redirectUri: process.env.REACT_APP_REDIRECT_URI || window.location.origin,
11+
scopes: ['openid', 'profile']
1212
});
1313

1414
const App = () => {

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"@testing-library/react": "^9.5.0",
4141
"@testing-library/user-event": "^7.2.1",
4242
"@types/jest": "^25.1.4",
43+
"@types/jwt-decode": "^2.2.1",
4344
"@types/node": "^12.12.38",
4445
"@types/react": "^16.9.27",
4546
"@types/react-dom": "^16.9.7",

src/AuthService.test.ts

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { AuthService, AuthTokens, AuthServiceProps } from './AuthService'
22

3+
// import tokens from './__fixtures__/tokens.json'
4+
35
const props: AuthServiceProps = {
46
clientId: 'testClientID',
57
clientSecret: undefined,
@@ -39,18 +41,8 @@ describe('AuthService', () => {
3941
})
4042
})
4143

42-
// it('it retrives a token', () => {
43-
// const mockJsonPromise = Promise.resolve(JSON.stringify(stubTokens))
44-
// const mockFetchPromise = Promise.resolve({
45-
// json: () => mockJsonPromise
46-
// })
47-
// jest.spyOn(global, 'fetch').mockImplementation(() => mockFetchPromise)
48-
// const fetchSpy: SpyInstance = jest.spyOn(global.prototype, 'fetch')
49-
50-
// const authorizationCode = 'authorizationCode'
51-
// authService.fetchToken(authorizationCode).then((tokens) => {
52-
// expect(tokens.accessToken).toContainEqual(stubTokens.accessToken)
53-
// expect(fetchSpy).toHaveBeenCalled()
54-
// })
44+
// it('it parses a token', () => {
45+
// window.localStorage.setItem('auth', tokens)
46+
// authService.getUser()
5547
// })
5648
})

src/AuthService.ts

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { createPKCECodes, PKCECodePair } from './pkce'
22
import { toUrlEncoded } from './util'
33

4+
import jwtDecode from 'jwt-decode'
5+
46
export interface AuthServiceProps {
57
clientId: string
68
clientSecret?: string
@@ -12,11 +14,18 @@ export interface AuthServiceProps {
1214
}
1315

1416
export interface AuthTokens {
15-
idToken: string
16-
accessToken: string
17-
refreshToken: string
18-
expiresIn: number
19-
tokenType: string
17+
id_token: string
18+
access_token: string
19+
refresh_token: string
20+
expires_in: number
21+
token_type: string
22+
}
23+
24+
export interface JWTIDToken {
25+
given_name: string
26+
family_name: string
27+
name: string
28+
email: string
2029
}
2130

2231
export class AuthService {
@@ -26,6 +35,13 @@ export class AuthService {
2635
this.props = props
2736
}
2837

38+
getUser(): {} {
39+
const t = this.getAuthTokens()
40+
if (null === t) return {}
41+
const decoded = jwtDecode(t.id_token) as {}
42+
return decoded
43+
}
44+
2945
getCodeFromLocation(location: Location): string | null {
3046
const split = location.toString().split('?')
3147
if (split.length < 2) {
@@ -93,16 +109,20 @@ export class AuthService {
93109
return window.localStorage.getItem('auth') !== null
94110
}
95111

96-
logout(): void {
112+
async logout(): Promise<void> {
97113
const { location } = this.props
98114
this.removeItem('pkce')
99115
this.removeItem('auth')
100116
location.reload()
101117
}
102118

119+
async login(): Promise<void> {
120+
this.authorize()
121+
}
122+
103123
// this will do a full page reload and to to the OAuth2 provider's login page and then redirect back to redirectUri
104124
authorize(): void {
105-
const { clientId, location, provider, redirectUri, scopes } = this.props
125+
const { clientId, provider, redirectUri, scopes } = this.props
106126

107127
const pkce = createPKCECodes()
108128
window.localStorage.setItem('pkce', JSON.stringify(pkce))
@@ -119,7 +139,7 @@ export class AuthService {
119139
}
120140
// Responds with a 302 redirect
121141
const url = `${provider}/authorize?${toUrlEncoded(query)}`
122-
location.replace(url)
142+
window.location.href = url
123143
}
124144

125145
// this happens after a full page reload. Read the code from localstorage

src/pkce.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { randomBytes, createHash } from 'crypto'
33
export type PKCECodePair = {
44
codeVerifier: string
55
codeChallenge: string
6+
createdAt: Date
67
}
78

89
export const base64URLEncode = (str: Buffer): string => {
@@ -20,9 +21,11 @@ export const sha256 = (buffer: Buffer): Buffer => {
2021
export const createPKCECodes = (): PKCECodePair => {
2122
const codeVerifier = base64URLEncode(randomBytes(64))
2223
const codeChallenge = base64URLEncode(sha256(Buffer.from(codeVerifier)))
24+
const createdAt = new Date()
2325
const codePair = {
2426
codeVerifier,
25-
codeChallenge
27+
codeChallenge,
28+
createdAt
2629
}
2730
return codePair
2831
}

0 commit comments

Comments
 (0)