-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
160 lines (118 loc) · 4.83 KB
/
index.js
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
const assert = require('assert');
const crypto = require('crypto');
const qs = require('querystring');
const URL = require('url');
const cheerio = require('cheerio');
const fetch = require('node-fetch');
const clientId = "pkce-test";
const redirectUri = 'http://localhost:1111/fake';
const keycloakUrl = "http://localhost:8080/auth/realms/test";
const urlBase64 = (content) => {
content = content.toString('base64');
const urlSafeReplacements = [
[/\+/g, '-'],
[/\//g, '_'],
[/=/g, '']
];
urlSafeReplacements.forEach(([test, replacement]) => {
content = content.replace(test, replacement);
});
return content;
};
const createCodeVerifier = () => urlBase64(crypto.randomBytes(32));
const createCodeChallenge = (verifier) => {
const hash = crypto.createHash('sha256').update(verifier).digest();
return urlBase64(hash);
};
const getAuthorizationCode = async (challenge) => {
const params = qs.stringify({
response_type: 'code',
scope: 'openid profile email',
client_id: clientId,
code_challenge: challenge,
code_challenge_method: 'S256',
redirect_uri: redirectUri
});
const loginPageResponse = await fetch(`${keycloakUrl}/protocol/openid-connect/auth?${params}`);
assert.strictEqual(loginPageResponse.status, 200, "Failed to retrieve login page");
const document = cheerio.load(await loginPageResponse.text());
const formAction = document('form').attr('action');
assert(formAction, "Failed to get form submission uri.");
const body = qs.stringify({
username: '[email protected]',
password: 'password'
});
const login = await fetch(formAction, {
body,
headers: {
'Cookie': loginPageResponse.headers.get('Set-Cookie'),
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
redirect: 'manual'
});
assert.strictEqual(login.status, 302, `Error submitting login form: ${await login.clone().text()}`);
const redirect = login.headers.get('location');
const authorizationCode = new URL.URLSearchParams(redirect).get('code');
assert(authorizationCode, "Authorization code not present in redirect uri");
return authorizationCode;
};
const exchangeCodeForTokens = (code, verifier, removeVerifier = false) => {
const body = {
grant_type: 'authorization_code',
client_id: clientId,
code_verifier: verifier,
code,
redirect_uri: redirectUri
};
if (removeVerifier) {
delete body.code_verifier;
}
return fetch(`${keycloakUrl}/protocol/openid-connect/token`, {
body: qs.stringify(body),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
redirect: 'manual'
});
};
const assertAuthorizationCodeFlowWithPkce = async () => {
const verifier = createCodeVerifier();
const challenge = createCodeChallenge(verifier);
const authorizationCode = await getAuthorizationCode(challenge);
const response = await exchangeCodeForTokens(authorizationCode, verifier);
assert.strictEqual(response.status, 200, "Failed to exchange code for tokens");
};
const assertExchangeWithIncorrectVerifier = async () => {
const verifier = createCodeVerifier();
const challenge = createCodeChallenge(verifier);
const authorizationCode = await getAuthorizationCode(challenge);
const response = await exchangeCodeForTokens(authorizationCode, "foobar");
assert.strictEqual(response.status, 400, "Should have failed exchange -- code verifier was invalid");
const {error_description} = await response.json();
assert.strictEqual(error_description, "PKCE invalid code verifier");
};
const assertExchangeWithNoVerifier = async () => {
const verifier = createCodeVerifier();
const challenge = createCodeChallenge(verifier);
const authorizationCode = await getAuthorizationCode(challenge);
const response = await exchangeCodeForTokens(authorizationCode, null, true);
assert.strictEqual(response.status, 400, "Should have failed exchange -- code verifier was not present");
const {error_description} = await response.json();
assert.strictEqual(error_description, "PKCE code verifier not specified");
};
(async () => {
try {
await assertAuthorizationCodeFlowWithPkce();
console.log('Finished authorization code flow with PKCE');
await assertExchangeWithIncorrectVerifier();
console.log('Verified that code cannot be exchanged when code verifier is invalid');
await assertExchangeWithNoVerifier();
console.log('Verified that code cannot be exchanged when code verifier is not present');
} catch (error) {
console.log(error.message);
process.exit(1);
}
})();