-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.ts
235 lines (204 loc) · 7.72 KB
/
index.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
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
/*
* @forgerock/javascript-sdk
*
* index.ts
*
* Copyright (c) 2020-2021 ForgeRock. All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import type { ConfigOptions } from '../config';
import Config from '../config';
import { FRLogger } from '../util/logger';
import type { OAuth2Tokens } from '../oauth2-client';
import OAuth2Client, { allowedErrors, ResponseType } from '../oauth2-client';
import type { StringDict, Tokens } from '../shared/interfaces';
import TokenStorage from '../token-storage';
import PKCE from '../util/pkce';
import { parseQuery } from '../util/url';
import { tokensWillExpireWithinThreshold } from './helpers';
interface GetTokensOptions extends ConfigOptions {
forceRenew?: boolean;
login?: 'embedded' | 'redirect' | undefined;
query?: StringDict<string>;
}
abstract class TokenManager {
/**
* Token Manager class that provides high-level abstraction for Authorization Code flow,
* PKCE value generation, token exchange and token storage.
*
* Supports both embedded authentication as well as external authentication via redirects
*
Example 1:
```js
const tokens = forgerock.TokenManager.getTokens({
forceRenew: true, // If you want to get new tokens, despite existing ones
login: 'embedded', // If user authentication is handled in-app
serverConfig: {
timeout: 5000, // If using "legacy", use a short timeout to catch error
},
});
```
Example 2:
```js
const tokens = forgerock.TokenManager.getTokens({
forceRenew: false, // Will immediately return stored tokens, if they exist
login: 'redirect', // If user authentication is handled in external Web app
});
```
Example 3:
```js
const tokens = forgerock.TokenManager.getTokens({
query: {
code: 'lFJQYdoQG1u7nUm8 ... ', // Authorization code from redirect URL
state: 'MTY2NDkxNTQ2Nde3D ... ', // State from redirect URL
},
});
```
*/
public static async getTokens(options?: GetTokensOptions): Promise<OAuth2Tokens | void> {
const { clientId, oauthThreshold } = Config.get(options as ConfigOptions);
// const storageKey = `${Config.get().prefix}-authflow-${clientId}`;
const storageKey = `${Config.get().prefix}-authflow-${clientId}`;
/**
* First, let's see if tokens exist locally
*/
const tokens = await TokenStorage.get();
/**
* If tokens are stored, no option for `forceRenew` or `query` object with `code`, and do not expire within the configured threshold,
* immediately return the stored tokens
*/
if (
tokens &&
!options?.forceRenew &&
!options?.query?.code &&
!tokensWillExpireWithinThreshold(oauthThreshold, tokens.tokenExpiry)
) {
return tokens;
}
/**
* If we are still here because of forceRenew or we have an authorization code, or the tokens expire within the configured threshold,
* revoke and delete existing tokens to prepare for the new ones
*/
if (tokens) {
try {
await OAuth2Client.revokeToken(options);
await TokenManager.deleteTokens();
} catch (error) {
FRLogger.warn('Existing tokens could not be revoked or deleted', error);
}
}
/**
* If authorization code and state are passed in, call token exchange
* and return acquired tokens
*/
if (options?.query?.code && options?.query?.state) {
const storedString = sessionStorage.getItem(storageKey);
sessionStorage.removeItem(storageKey);
const storedValues: { state: string; verifier: string } = JSON.parse(storedString as string);
return await this.tokenExchange(options, storedValues);
}
/**
* If we are here, then we are just beginning the auth code flow,
* so let's generate authorize PKCE values and URL
*/
const verifier = PKCE.createVerifier();
const state = PKCE.createState();
// so to not change the type of the above function
// we assign it here if its undefined or null.
const config = Object.assign({}, options);
delete config.forceRenew;
delete config.login;
const authorizeUrlOptions = {
...config,
responseType: ResponseType.Code,
state,
verifier,
};
/**
* Attempt to call the authorize URL to retrieve authorization code
*/
try {
// Check expected browser support
// To support legacy browsers, iframe works best with short timeout
const parsedUrl = new URL(await OAuth2Client.getAuthCodeByIframe(authorizeUrlOptions));
// Throw if we have an error param or have no authorization code
if (parsedUrl.searchParams.get('error')) {
throw Error(`${parsedUrl.searchParams.get('error_description')}`);
} else if (!parsedUrl.searchParams.get('code')) {
throw Error(allowedErrors.AuthenticationConsentRequired);
}
const parsedQuery = parseQuery(parsedUrl.toString());
if (!options) {
options = {};
}
options.query = parsedQuery;
} catch (err) {
// If authorize request fails, handle according to `login` type
if (!(err instanceof Error) || options?.login !== 'redirect') {
// Throw for any error if login is NOT of type "redirect"
throw err;
}
// Check if error is not one of our allowed errors
if (
allowedErrors.AuthenticationConsentRequired !== err.message &&
allowedErrors.AuthorizationTimeout !== err.message &&
allowedErrors.FailedToFetch !== err.message &&
allowedErrors.NetworkError !== err.message &&
allowedErrors.InteractionNotAllowed !== err.message &&
// Check for Ping Identity Login Required error
// Long message, so just check substring
!err.message.includes(allowedErrors.LoginRequired) &&
// Safari has a very long error message, so we check for a substring
!err.message.includes(allowedErrors.CORSError)
) {
// Throw if the error is NOT an explicitly allowed error along with redirect of true
// as that is a normal response and just requires a redirect
throw err;
}
// Since `login` is configured for "redirect", store authorize values and redirect
sessionStorage.setItem(storageKey, JSON.stringify(authorizeUrlOptions));
const authorizeUrl = await OAuth2Client.createAuthorizeUrl(authorizeUrlOptions);
return location.assign(authorizeUrl);
}
/**
* Exchange authorization code for tokens
*/
return await this.tokenExchange(options, { state, verifier });
}
public static async deleteTokens(): Promise<void> {
await TokenStorage.remove();
}
private static async tokenExchange(
options: GetTokensOptions,
stored: { state: string; verifier: string },
): Promise<Tokens> {
/**
* Ensure incoming state and stored state are equal and authorization code exists
*/
if (options.query?.state !== stored.state) {
throw new Error('State mismatch');
}
if (!options.query?.code || Array.isArray(options.query?.code)) {
throw new Error('Failed to acquire authorization code');
}
/**
* Generate token exchange options
*/
const authorizationCode = options.query?.code;
const verifier = stored.verifier;
const getTokensOptions = { ...options, authorizationCode, verifier };
const tokens = await OAuth2Client.getOAuth2Tokens(getTokensOptions);
if (!tokens || !tokens.accessToken) {
throw new Error('Unable to exchange authorization for tokens');
}
try {
await TokenStorage.set(tokens);
} catch (error) {
FRLogger.error('Failed to store tokens', error);
}
return tokens;
}
}
export default TokenManager;
export type { GetTokensOptions };