-
Notifications
You must be signed in to change notification settings - Fork 9
/
lib.js
281 lines (243 loc) · 9.85 KB
/
lib.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
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
/*!
* Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
const jwksClient = require('jwks-rsa');
const nJwt = require('njwt');
class ConfigurationValidationError extends Error {}
const findDomainURL = 'https://bit.ly/finding-okta-domain';
const findAppCredentialsURL = 'https://bit.ly/finding-okta-app-credentials';
const assertIssuer = (issuer, testing = {}) => {
const isHttps = new RegExp('^https://');
const hasDomainAdmin = /-admin.(okta|oktapreview|okta-emea).com/;
const copyMessage = 'You can copy your domain from the Okta Developer ' +
'Console. Follow these instructions to find it: ' + findDomainURL;
if (testing.disableHttpsCheck) {
const httpsWarning = 'Warning: HTTPS check is disabled. ' +
'This allows for insecure configurations and is NOT recommended for production use.';
/* eslint-disable-next-line no-console */
console.warn(httpsWarning);
}
if (!issuer) {
throw new ConfigurationValidationError('Your Okta URL is missing. ' + copyMessage);
} else if (!testing.disableHttpsCheck && !issuer.match(isHttps)) {
throw new ConfigurationValidationError(
'Your Okta URL must start with https. ' +
`Current value: ${issuer}. ${copyMessage}`
);
} else if (issuer.match(/{yourOktaDomain}/)) {
throw new ConfigurationValidationError('Replace {yourOktaDomain} with your Okta domain. ' + copyMessage);
} else if (issuer.match(hasDomainAdmin)) {
throw new ConfigurationValidationError(
'Your Okta domain should not contain -admin. ' +
`Current value: ${issuer}. ${copyMessage}`
);
}
};
const assertClientId = (clientId) => {
const copyCredentialsMessage = 'You can copy it from the Okta Developer Console ' +
'in the details for the Application you created. ' +
`Follow these instructions to find it: ${findAppCredentialsURL}`;
if (!clientId) {
throw new ConfigurationValidationError('Your client ID is missing. ' + copyCredentialsMessage);
} else if (clientId.match(/{clientId}/)) {
throw new ConfigurationValidationError(
'Replace {clientId} with the client ID of your Application. ' + copyCredentialsMessage);
}
};
class AssertedClaimsVerifier {
constructor() {
this.errors = [];
}
extractOperator(claim) {
const idx = claim.indexOf('.');
if (idx >= 0) {
return claim.substring(idx + 1);
}
return undefined;
}
extractClaim(claim) {
const idx = claim.indexOf('.');
if (idx >= 0) {
return claim.substring(0, idx);
}
return claim;
}
isValidOperator(operator) {
// may support more operators in the future
return !operator || operator === 'includes';
}
checkAssertions(op, claim, expectedValue, actualValue) {
if (!op && actualValue !== expectedValue) {
this.errors.push(`claim '${claim}' value '${actualValue}' does not match expected value '${expectedValue}'`);
} else if (op === 'includes' && Array.isArray(expectedValue)) {
expectedValue.forEach((value) => {
if (!actualValue || !actualValue.includes(value)) {
this.errors.push(`claim '${claim}' value '${actualValue}' does not include expected value '${value}'`);
}
});
} else if (op === 'includes' && (!actualValue || !actualValue.includes(expectedValue))) {
this.errors.push(`claim '${claim}' value '${actualValue}' does not include expected value '${expectedValue}'`);
}
}
}
function verifyAssertedClaims(verifier, claims) {
const assertedClaimsVerifier = new AssertedClaimsVerifier();
for (const [claimName, expectedValue] of Object.entries(verifier.claimsToAssert)) {
const operator = assertedClaimsVerifier.extractOperator(claimName);
if (!assertedClaimsVerifier.isValidOperator(operator)) {
throw new Error(`operator: '${operator}' invalid. Supported operators: 'includes'.`);
}
const claim = assertedClaimsVerifier.extractClaim(claimName);
const actualValue = claims[claim];
assertedClaimsVerifier.checkAssertions(operator, claim, expectedValue, actualValue);
}
if (assertedClaimsVerifier.errors.length) {
throw new Error(assertedClaimsVerifier.errors.join(', '));
}
}
function verifyAudience(expected, aud) {
if (!expected) {
throw new Error('expected audience is required');
}
if (!Array.isArray(aud)) {
if (Array.isArray(expected) && !expected.includes(aud)) {
throw new Error(`audience claim ${aud} does not match one of the expected audiences: ${expected.join(', ')}`);
}
if (!Array.isArray(expected) && aud !== expected) {
throw new Error(`audience claim ${aud} does not match expected audience: ${expected}`);
}
} else {
if (Array.isArray(expected) && !(aud.some(val => expected.includes(val)))) {
throw new Error(`audience claims ${aud.join(', ')} do not match one of the expected audiences: ${expected}`);
}
if (!Array.isArray(expected) && !aud.includes(expected)) {
throw new Error(`audience claims ${aud.join(', ')} do not include expected audience: ${expected}`);
}
}
}
function verifyClientId(expected, aud) {
if (!expected) {
throw new Error('expected client id is required');
}
assertClientId(expected);
if (aud !== expected) {
throw new Error(`audience claim ${aud} does not match expected client id: ${expected}`);
}
}
function verifyIssuer(expected, issuer) {
if (issuer !== expected) {
throw new Error(`issuer ${issuer} does not match expected issuer: ${expected}`);
}
}
function verifyNonce(expected, nonce) {
if (nonce && !expected) {
throw new Error('expected nonce is required');
}
if (!nonce && expected) {
throw new Error(`nonce claim is missing but expected: ${expected}`);
}
if (nonce && expected && nonce !== expected) {
throw new Error(`nonce claim ${nonce} does not match expected nonce: ${expected}`);
}
}
function getJwksUri(options) {
return options.jwksUri ? options.jwksUri : options.issuer + '/v1/keys';
}
class OktaJwtVerifier {
constructor(options = {}) {
// Assert configuration options exist and are well-formed (not necessarily correct!)
assertIssuer(options.issuer, options.testing);
if (options.clientId) {
assertClientId(options.clientId);
}
// https://github.com/auth0/node-jwks-rsa/blob/master/CHANGELOG.md#request-agent-options
if (options.requestAgentOptions) {
// jwks-rsa no longer accepts 'requestAgentOptions' and instead requires a http(s).Agent be passed directly
const msg = `\`requestAgentOptions\` has been deprecated, use \`requestAgent\` instead.
For more info see https://github.com/auth0/node-jwks-rsa/blob/master/CHANGELOG.md#request-agent-options`;
throw new ConfigurationValidationError(msg);
}
this.claimsToAssert = options.assertClaims || {};
this.issuer = options.issuer;
this.jwksUri = getJwksUri(options);
this.jwksClient = jwksClient({
jwksUri: this.jwksUri,
cache: true,
cacheMaxAge: options.cacheMaxAge || (60 * 60 * 1000),
cacheMaxEntries: 3,
jwksRequestsPerMinute: options.jwksRequestsPerMinute || 10,
rateLimit: true,
// https://github.com/auth0/node-jwks-rsa/blob/master/CHANGELOG.md#request-agent-options
// requestAgentOptions: options.requestAgentOptions, !! DEPRECATED !!
requestAgent: options.requestAgent,
getKeysInterceptor: options.getKeysInterceptor,
});
this.verifier = nJwt.createVerifier().setSigningAlgorithm('RS256').withKeyResolver((kid, cb) => {
if (kid) {
this.jwksClient.getSigningKey(kid, (err, key) => {
cb(err, key && (key.publicKey || key.rsaPublicKey));
});
} else {
cb('No KID specified', null);
}
});
}
async verifyAsPromise(tokenString) {
return new Promise((resolve, reject) => {
// Convert to a promise
this.verifier.verify(tokenString, (err, jwt) => {
if (err) {
return reject(err);
}
const oktaJwt = {
header: { ...jwt.header },
claims: { ...jwt.body },
toString: () => tokenString,
isExpired: () => jwt.isExpired(),
isNotBefore: () => jwt.isNotBefore()
};
Object.freeze(oktaJwt.header);
Object.freeze(oktaJwt.claims);
Object.freeze(oktaJwt);
resolve(oktaJwt);
});
});
}
async verifyAccessToken(accessTokenString, expectedAudience) {
// njwt verifies expiration and signature.
// We require RS256 in the base verifier.
// Remaining to verify:
// - audience claim
// - issuer claim
// - any custom claims passed in
const jwt = await this.verifyAsPromise(accessTokenString);
verifyAudience(expectedAudience, jwt.claims.aud);
verifyIssuer(this.issuer, jwt.claims.iss);
verifyAssertedClaims(this, jwt.claims);
return jwt;
}
async verifyIdToken(idTokenString, expectedClientId, expectedNonce) {
// njwt verifies expiration and signature.
// We require RS256 in the base verifier.
// Remaining to verify:
// - audience claim (must match client id)
// - issuer claim
// - nonce claim (if present)
// - any custom claims passed in
const jwt = await this.verifyAsPromise(idTokenString);
verifyClientId(expectedClientId, jwt.claims.aud);
verifyIssuer(this.issuer, jwt.claims.iss);
verifyNonce(expectedNonce, jwt.claims.nonce);
verifyAssertedClaims(this, jwt.claims);
return jwt;
}
}
module.exports = OktaJwtVerifier;