-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
par.ts
80 lines (67 loc) · 2.24 KB
/
par.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
import * as client from 'openid-client'
// Prerequisites
let getCurrentUrl!: (...args: any) => URL
let server!: URL // Authorization server's Issuer Identifier URL
let clientId!: string
let clientSecret!: string
/**
* Value used in the authorization request as redirect_uri pre-registered at the
* Authorization Server.
*/
let redirect_uri!: string
// End of prerequisites
let config = await client.discovery(server, clientId, clientSecret)
let code_challenge_method = 'S256'
/**
* The following (code_verifier and potentially state) MUST be generated for
* every redirect to the authorization_endpoint. You must store the
* code_verifier and state in the end-user session such that it can be recovered
* as the user gets redirected from the authorization server back to your
* application.
*/
let code_verifier = client.randomPKCECodeVerifier()
let code_challenge = await client.calculatePKCECodeChallenge(code_verifier)
let state!: string
{
// redirect user to as.authorization_endpoint
let parameters: Record<string, string> = {
redirect_uri,
scope: 'api:read',
code_challenge,
code_challenge_method,
}
/**
* We cannot be sure the AS supports PKCE so we're going to use state too. Use
* of PKCE is backwards compatible even if the AS doesn't support it which is
* why we're using it regardless.
*/
if (!config.serverMetadata().supportsPKCE()) {
state = client.randomState()
parameters.state = state
}
let redirectTo = await client.buildAuthorizationUrlWithPAR(config, parameters)
console.log('redirecting to', redirectTo.href)
// now redirect the user to redirectTo.href
}
// one eternity later, the user lands back on the redirect_uri
// Authorization Code Grant
let access_token: string
{
let currentUrl: URL = getCurrentUrl()
let tokens = await client.authorizationCodeGrant(config, currentUrl, {
pkceCodeVerifier: code_verifier,
expectedState: state,
})
console.log('Token Endpoint Response', tokens)
;({ access_token } = tokens)
}
// Protected Resource Request
{
let protectedResource = await client.fetchProtectedResource(
config,
access_token,
new URL('https://rs.example.com/api'),
'GET',
)
console.log('Protected Resource Response', await protectedResource.json())
}