-
Notifications
You must be signed in to change notification settings - Fork 315
Expand file tree
/
Copy pathoauth.ts
More file actions
659 lines (594 loc) · 19.6 KB
/
oauth.ts
File metadata and controls
659 lines (594 loc) · 19.6 KB
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
658
659
import {
InitOverride,
JSONApiResponse,
VoidApiResponse,
validateRequiredRequestParams,
} from '../lib/runtime.js';
import { BaseAuthAPI, AuthenticationClientOptions, grant } from './base-auth-api.js';
import { IDTokenValidateOptions, IDTokenValidator } from './id-token-validator.js';
import { mtlsPrefix } from '../utils.js';
interface AuthorizationDetails {
readonly type: string;
readonly [parameter: string]: unknown;
}
export interface TokenSet<
TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails
> {
/**
* The access token.
*/
access_token: string;
/**
* The refresh token, available with the `offline_access` scope.
*/
refresh_token?: string;
/**
* The user's ID Token.
*/
id_token?: string;
/**
* The token type of the access token.
*/
token_type: 'Bearer';
/**
* The duration in secs that the access token is valid.
*/
expires_in: number;
/**
* The authorization details when using Rich Authorization Requests (RAR).
* @see https://auth0.com/docs/get-started/apis/configure-rich-authorization-requests
*/
authorization_details?: TAuthorizationDetails[];
}
export interface GrantOptions {
idTokenValidateOptions?: Pick<IDTokenValidateOptions, 'organization'>;
initOverrides?: InitOverride;
}
export interface AuthorizationCodeGrantOptions {
idTokenValidateOptions?: IDTokenValidateOptions;
initOverrides?: InitOverride;
}
export interface ClientCredentials {
/**
* Specify this to override the parent class's `clientId`
*/
client_id?: string;
/**
* Specify this to override the parent class's `clientSecret`
*/
client_secret?: string;
/**
* Specify this to provide your own client assertion JWT rather than
* the class creating one for you from the `clientAssertionSigningKey`.
*/
client_assertion?: string;
/**
* If you provide your own `client_assertion` you should also provide
* the `client_assertion_type`.
*/
client_assertion_type?: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
}
export interface AuthorizationCodeGrantRequest extends ClientCredentials {
/**
* The Authorization Code received from the initial `/authorize` call.
*/
code: string;
/**
* This is required only if it was set at the `/authorize` endpoint. The values must match.
*/
redirect_uri?: string;
/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;
}
export interface AuthorizationCodeGrantWithPKCERequest extends AuthorizationCodeGrantRequest {
/**
* Cryptographically random key that was used to generate the code_challenge passed to `/authorize`.
*/
code_verifier: string;
}
/**
* Represents a request for a client credentials grant in the OAuth 2.0 framework, specific to Auth0 implementation.
*
* @property audience - The unique identifier of the target API you want to access.
* @property organization - The identifier of the organization for which the request is being made.
*/
export interface ClientCredentialsGrantRequest extends ClientCredentials {
/**
* The unique identifier of the target API you want to access.
*/
audience: string;
organization?: string;
}
export interface PushedAuthorizationRequest<
TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails
> extends ClientCredentials {
/**
* URI to redirect to.
*/
redirect_uri: string;
/**
* The response_type the client expects.
*/
response_type: string;
/**
* The response_mode to use.
*/
response_mode?: string;
/**
* The nonce.
*/
nonce?: string;
/**
* State value to be passed back on successful authorization.
*/
state?: string;
/**
* Name of the connection.
*/
connection?: string;
/**
* Scopes to request. Multiple scopes must be separated by a space character.
*/
scope?: string;
/**
* The unique identifier of the target API you want to access.
*/
audience?: string;
/**
* The organization to log the user in to.
*/
organization?: string;
/**
* The id of an invitation to accept.
*/
invitation?: string;
/**
* A Base64-encoded SHA-256 hash of the {@link AuthorizationCodeGrantWithPKCERequest.code_verifier} used for the Authorization Code Flow with PKCE.
*/
code_challenge?: string;
/**
* Allows JWT-Secured Authorization Request (JAR), when JAR & PAR request are used together. {@link https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-par-and-jar | Reference}
*/
request?: string;
/**
* A JSON stringified array of objects. It can carry fine-grained authorization data in OAuth messages as part of Rich Authorization Requests (RAR) {@link https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-rar | Reference}
*/
authorization_details?: string | TAuthorizationDetails[];
/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;
}
export interface PushedAuthorizationResponse {
/**
* The request URI corresponding to the authorization request posted.
* This URI is a single-use reference to the respective request data in the subsequent authorization request.
*/
request_uri: string;
/**
* This URI is a single-use reference to the respective request data in the subsequent authorization request.
*/
expires_in: number;
}
export interface PasswordGrantRequest extends ClientCredentials {
/**
* The unique identifier of the target API you want to access.
*/
audience?: string;
/**
* Resource Owner's identifier, such as a username or email address.
*/
username: string;
/**
* Resource Owner's secret.
*/
password: string;
/**
* String value of the different scopes the application is asking for. Multiple scopes are separated with whitespace.
*/
scope?: string;
/**
* String value of the realm the user belongs. Set this if you want to add realm support at this grant.
* For more information on what realms are refer to https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow#realm-support.
*/
realm?: string;
}
export interface DeviceCodeGrantRequest {
/**
* Specify this to override the parent class's `clientId`
*/
client_id?: string;
/**
* The device code previously returned from the `/oauth/device/code` endpoint.
*/
device_code: string;
}
export interface RefreshTokenGrantRequest extends ClientCredentials {
/**
* The Refresh Token to use.
*/
refresh_token: string;
/**
* A space-delimited list of requested scope permissions.
* If not sent, the original scopes will be used; otherwise you can request a reduced set of scopes.
*/
scope?: string;
/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;
}
export interface RevokeRefreshTokenRequest extends ClientCredentials {
/**
* The Refresh Token you want to revoke.
*/
token: string;
}
export interface TokenExchangeGrantRequest {
/**
* Specify this to override the parent class's `clientId`
*/
client_id?: string;
/**
* Externally-issued identity artifact, representing the user.
*/
subject_token: string;
/**
* The unique identifier of the target API you want to access.
*/
audience?: string;
/**
* String value of the different scopes the application is requesting.
* Multiple scopes are separated with whitespace.
*/
scope?: string;
/**
* Optional element used for native iOS interactions for which profile updates can occur.
* Expected parameter value will be JSON in the form of: `{ name: { firstName: 'John', lastName: 'Smith }}`
*/
user_profile: string;
}
/**
* Options to exchange a federated connection token.
*/
export interface TokenForConnectionRequest {
/**
* The subject token(refresh token in this case) to exchange for an access token for a connection.
*/
subject_token: string;
/**
* The target social provider connection (e.g., "google-oauth2").
*/
connection: string;
/**
* Optional login hint
*/
login_hint?: string;
}
export interface TokenForConnectionResponse {
access_token: string;
scope?: string;
expires_at: number; // the time at which the access token expires in seconds since epoch
connection: string;
[key: string]: unknown;
}
export const TOKEN_FOR_CONNECTION_GRANT_TYPE =
'urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token';
export const TOKEN_FOR_CONNECTION_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:refresh_token';
export const TOKEN_FOR_CONNECTION_REQUESTED_TOKEN_TYPE =
'http://auth0.com/oauth/token-type/federated-connection-access-token';
export const TOKEN_URL = '/oauth/token';
/**
* OAuth 2.0 flows.
*/
export class OAuth extends BaseAuthAPI {
readonly idTokenValidator: IDTokenValidator;
constructor(options: AuthenticationClientOptions) {
super({
...options,
domain: options.useMTLS ? `${mtlsPrefix}.${options.domain}` : options.domain,
});
this.idTokenValidator = new IDTokenValidator(options);
}
/**
* This is the flow that regular web apps use to access an API.
*
* Use this endpoint to exchange an Authorization Code for a Token.
*
* See: https://auth0.com/docs/api/authentication#authorization-code-flow44
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId',
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.authorizationCodeGrant({ code: 'mycode' });
* ```
*/
async authorizationCodeGrant(
bodyParameters: AuthorizationCodeGrantRequest,
options: AuthorizationCodeGrantOptions = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['code']);
return grant(
'authorization_code',
await this.addClientAuthentication(bodyParameters),
options,
this.clientId,
this.idTokenValidator,
this.request.bind(this)
);
}
/**
* PKCE was originally designed to protect the authorization code flow in mobile apps,
* but its ability to prevent authorization code injection makes it useful for every type of OAuth client,
* even web apps that use client authentication.
*
* See: https://auth0.com/docs/api/authentication#authorization-code-flow-with-pkce45
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId',
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.authorizationCodeGrantWithPKCE({
* code: 'mycode',
* code_verifier: 'mycodeverifier'
* });
* ```
*/
async authorizationCodeGrantWithPKCE(
bodyParameters: AuthorizationCodeGrantWithPKCERequest,
options: AuthorizationCodeGrantOptions = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['code', 'code_verifier']);
return grant(
'authorization_code',
await this.addClientAuthentication(bodyParameters),
options,
this.clientId,
this.idTokenValidator,
this.request.bind(this)
);
}
/**
* This is the OAuth 2.0 grant that server processes use to access an API.
*
* Use this endpoint to directly request an Access Token by using the Client's credentials
* (a Client ID and a Client Secret or a Client Assertion).
*
* See: https://auth0.com/docs/api/authentication#client-credentials-flow
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId',
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.clientCredentialsGrant({ audience: 'myaudience' });
* ```
*/
async clientCredentialsGrant(
bodyParameters: ClientCredentialsGrantRequest,
options: { initOverrides?: InitOverride } = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['audience']);
return grant(
'client_credentials',
await this.addClientAuthentication(bodyParameters),
options,
this.clientId,
this.idTokenValidator,
this.request.bind(this)
);
}
/**
* This is the OAuth 2.0 extension that allows to initiate an OAuth flow from the backchannel instead of by building a URL.
*
*
* See: https://www.rfc-editor.org/rfc/rfc9126.html
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId',
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.pushedAuthorization({ response_type: 'id_token', redirect_uri: 'http://localhost' });
* ```
*/
async pushedAuthorization(
bodyParameters: PushedAuthorizationRequest,
options: { initOverrides?: InitOverride } = {}
): Promise<JSONApiResponse<PushedAuthorizationResponse>> {
validateRequiredRequestParams(bodyParameters, ['client_id', 'response_type', 'redirect_uri']);
const { authorization_details } = bodyParameters;
if (authorization_details) {
// Convert to string if not already
bodyParameters.authorization_details =
typeof authorization_details !== 'string'
? JSON.stringify(authorization_details)
: authorization_details;
}
const bodyParametersWithClientAuthentication = await this.addClientAuthentication(
bodyParameters
);
const response = await this.request(
{
path: '/oauth/par',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: this.clientId,
...bodyParametersWithClientAuthentication,
}),
},
options.initOverrides
);
return JSONApiResponse.fromResponse(response);
}
/**
* This information is typically received from a highly trusted public client like a SPA*.
* (<strong>*Note:</string> For single-page applications and native/mobile apps, we recommend using web flows instead.)
*
* See: https://auth0.com/docs/api/authentication#resource-owner-password
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId'
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.passwordGrant({
* username: '[email protected]',
* password: 'mypassword'
* },
* { initOverrides: { headers: { 'auth0-forwarded-for': 'END.USER.IP.123' } } }
* );
* ```
*
* Set the'auth0-forwarded-for' header to the end-user IP as a string value if you want
* brute-force protection to work in server-side scenarios.
*
* See https://auth0.com/docs/get-started/authentication-and-authorization-flow/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection
*
*/
async passwordGrant(
bodyParameters: PasswordGrantRequest,
options: GrantOptions = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['username', 'password']);
return grant(
bodyParameters.realm ? 'http://auth0.com/oauth/grant-type/password-realm' : 'password',
await this.addClientAuthentication(bodyParameters),
options,
this.clientId,
this.idTokenValidator,
this.request.bind(this)
);
}
/**
* Use this endpoint to refresh an Access Token using the Refresh Token you got during authorization.
*
* See: https://auth0.com/docs/api/authentication#refresh-token
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId'
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.refreshTokenGrant({ refresh_token: 'myrefreshtoken' })
* ```
*/
async refreshTokenGrant(
bodyParameters: RefreshTokenGrantRequest,
options: GrantOptions = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['refresh_token']);
return grant(
'refresh_token',
await this.addClientAuthentication(bodyParameters),
options,
this.clientId,
this.idTokenValidator,
this.request.bind(this)
);
}
/**
* Use this endpoint to invalidate a Refresh Token if it has been compromised.
*
* The behaviour of this endpoint depends on the state of the <a href="https://auth0.com/docs/secure/tokens/refresh-tokens/revoke-refresh-tokens#refresh-tokens-and-grants">Refresh Token Revocation Deletes Grant</a> toggle.
* If this toggle is enabled, then each revocation request invalidates not only the specific token, but all other tokens based on the same authorization grant.
* This means that all Refresh Tokens that have been issued for the same user, application, and audience will be revoked.
* If this toggle is disabled, then only the refresh token is revoked, while the grant is left intact.
*
* See: https://auth0.com/docs/api/authentication#revoke-refresh-token
*
* @example
* ```js
* const auth0 = new AuthenticationApi({
* domain: 'my-domain.auth0.com',
* clientId: 'myClientId'
* clientSecret: 'myClientSecret'
* });
*
* await auth0.oauth.revokeRefreshToken({ token: 'myrefreshtoken' })
* ```
*/
async revokeRefreshToken(
bodyParameters: RevokeRefreshTokenRequest,
options: { initOverrides?: InitOverride } = {}
): Promise<VoidApiResponse> {
validateRequiredRequestParams(bodyParameters, ['token']);
const response = await this.request(
{
path: '/oauth/revoke',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: await this.addClientAuthentication({ client_id: this.clientId, ...bodyParameters }),
},
options.initOverrides
);
return VoidApiResponse.fromResponse(response);
}
/**
* Exchanges a subject token (refresh token in this case) for an access token for the connection.
*
* The request body includes:
* - client_id (and client_secret/client_assertion via addClientAuthentication)
* - grant_type set to `urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token`
* - subject_token (refresh token) and fixed subject_token_type for refresh tokens (`urn:ietf:params:oauth:token-type:refresh_token`)
* - requested_token_type (`http://auth0.com/oauth/token-type/federated-connection-access-token`) indicating that a federated connection access token is desired
* - connection name and an optional `login_hint` if provided
*
* @param bodyParameters - The options to retrieve a token for a connection.
* @returns A promise with the token response data.
* @throws An error if the exchange fails.
*/
public async tokenForConnection(
bodyParameters: TokenForConnectionRequest,
options: { initOverrides?: InitOverride } = {}
): Promise<JSONApiResponse<TokenSet>> {
validateRequiredRequestParams(bodyParameters, ['connection', 'subject_token']);
const body: Record<string, string> = {
...bodyParameters,
grant_type: TOKEN_FOR_CONNECTION_GRANT_TYPE,
subject_token_type: TOKEN_FOR_CONNECTION_TOKEN_TYPE,
requested_token_type: TOKEN_FOR_CONNECTION_REQUESTED_TOKEN_TYPE,
};
await this.addClientAuthentication(body);
const response = await this.request(
{
path: TOKEN_URL,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(body),
},
options.initOverrides
);
return JSONApiResponse.fromResponse(response);
}
}