-
Notifications
You must be signed in to change notification settings - Fork 290
Expand file tree
/
Copy pathauth0-provider.tsx
More file actions
403 lines (373 loc) · 11.1 KB
/
auth0-provider.tsx
File metadata and controls
403 lines (373 loc) · 11.1 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
import React, {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react';
import {
Auth0Client,
Auth0ClientOptions,
PopupLoginOptions,
PopupConfigOptions,
GetTokenWithPopupOptions,
RedirectLoginResult,
GetTokenSilentlyOptions,
User,
RedirectConnectAccountOptions,
ConnectAccountRedirectResult,
ResponseType,
CustomTokenExchangeOptions,
TokenEndpointResponse
} from '@auth0/auth0-spa-js';
import Auth0Context, {
Auth0ContextInterface,
LogoutOptions,
RedirectLoginOptions,
} from './auth0-context';
import {
hasAuthParams,
loginError,
tokenError,
deprecateRedirectUri,
} from './utils';
import { reducer } from './reducer';
import { initialAuthState, type AuthState } from './auth-state';
/**
* The account that has been connected during the connect flow.
*/
export type ConnectedAccount = Omit<ConnectAccountRedirectResult, 'appState' | 'response_type'>;
/**
* The state of the application before the user was redirected to the login page
* and any account that the user may have connected to.
*/
export type AppState = {
returnTo?: string;
connectedAccount?: ConnectedAccount;
response_type?: ResponseType;
[key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
};
/**
* The main configuration to instantiate the `Auth0Provider`.
*/
export interface Auth0ProviderOptions<TUser extends User = User> extends Auth0ClientOptions {
/**
* The child nodes your Provider has wrapped
*/
children?: React.ReactNode;
/**
* By default this removes the code and state parameters from the url when you are redirected from the authorize page.
* It uses `window.history` but you might want to overwrite this if you are using a custom router, like `react-router-dom`
* See the EXAMPLES.md for more info.
*/
onRedirectCallback?: (appState?: AppState, user?: TUser) => void;
/**
* By default, if the page url has code/state params, the SDK will treat them as Auth0's and attempt to exchange the
* code for a token. In some cases the code might be for something else (another OAuth SDK perhaps). In these
* instances you can instruct the client to ignore them eg
*
* ```jsx
* <Auth0Provider
* clientId={clientId}
* domain={domain}
* skipRedirectCallback={window.location.pathname === '/stripe-oauth-callback'}
* >
* ```
*/
skipRedirectCallback?: boolean;
/**
* Context to be used when creating the Auth0Provider, defaults to the internally created context.
*
* This allows multiple Auth0Providers to be nested within the same application, the context value can then be
* passed to useAuth0, withAuth0, or withAuthenticationRequired to use that specific Auth0Provider to access
* auth state and methods specifically tied to the provider that the context belongs to.
*
* When using multiple Auth0Providers in a single application you should do the following to ensure sessions are not
* overwritten:
*
* * Configure a different redirect_uri for each Auth0Provider, and set skipRedirectCallback for each provider to ignore
* the others redirect_uri
* * If using localstorage for both Auth0Providers, ensure that the audience and scope are different for so that the key
* used to store data is different
*
* For a sample on using multiple Auth0Providers review the [React Account Linking Sample](https://github.com/auth0-samples/auth0-link-accounts-sample/tree/react-variant)
*/
context?: React.Context<Auth0ContextInterface<TUser>>;
}
/**
* Replaced by the package version at build time.
* @ignore
*/
declare const __VERSION__: string;
/**
* @ignore
*/
const toAuth0ClientOptions = (
opts: Auth0ProviderOptions
): Auth0ClientOptions => {
deprecateRedirectUri(opts);
return {
...opts,
auth0Client: {
name: 'auth0-react',
version: __VERSION__,
},
};
};
/**
* @ignore
*/
const defaultOnRedirectCallback = (appState?: AppState): void => {
window.history.replaceState(
{},
document.title,
appState!.returnTo ?? window.location.pathname
);
};
/**
* ```jsx
* <Auth0Provider
* domain={domain}
* clientId={clientId}
* authorizationParams={{ redirect_uri: window.location.origin }}>
* <MyApp />
* </Auth0Provider>
* ```
*
* Provides the Auth0Context to its child components.
*/
const Auth0Provider = <TUser extends User = User>(opts: Auth0ProviderOptions<TUser>) => {
const {
children,
skipRedirectCallback,
onRedirectCallback = defaultOnRedirectCallback,
context = Auth0Context,
...clientOpts
} = opts;
const [client] = useState(
() => new Auth0Client(toAuth0ClientOptions(clientOpts))
);
const [state, dispatch] = useReducer(reducer<TUser>, initialAuthState as AuthState<TUser>);
const didInitialise = useRef(false);
const handleError = useCallback((error: Error) => {
dispatch({ type: 'ERROR', error });
return error;
}, []);
useEffect(() => {
if (didInitialise.current) {
return;
}
didInitialise.current = true;
(async (): Promise<void> => {
try {
let user: TUser | undefined;
if (hasAuthParams() && !skipRedirectCallback) {
const { appState = {}, response_type, ...result } = await client.handleRedirectCallback();
user = await client.getUser();
appState.response_type = response_type;
if (response_type === ResponseType.ConnectCode) {
appState.connectedAccount = result as ConnectedAccount;
}
onRedirectCallback(appState, user);
} else {
await client.checkSession();
user = await client.getUser();
}
dispatch({ type: 'INITIALISED', user });
} catch (error) {
handleError(loginError(error));
}
})();
}, [client, onRedirectCallback, skipRedirectCallback, handleError]);
const loginWithRedirect = useCallback(
(opts?: RedirectLoginOptions): Promise<void> => {
deprecateRedirectUri(opts);
return client.loginWithRedirect(opts);
},
[client]
);
const loginWithPopup = useCallback(
async (
options?: PopupLoginOptions,
config?: PopupConfigOptions
): Promise<void> => {
dispatch({ type: 'LOGIN_POPUP_STARTED' });
try {
await client.loginWithPopup(options, config);
} catch (error) {
handleError(loginError(error));
return;
}
const user = await client.getUser();
dispatch({ type: 'LOGIN_POPUP_COMPLETE', user });
},
[client, handleError]
);
const logout = useCallback(
async (opts: LogoutOptions = {}): Promise<void> => {
await client.logout(opts);
if (opts.openUrl || opts.openUrl === false) {
dispatch({ type: 'LOGOUT' });
}
},
[client]
);
const getAccessTokenSilently = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (opts?: GetTokenSilentlyOptions): Promise<any> => {
let token;
try {
token = await client.getTokenSilently(opts);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'GET_ACCESS_TOKEN_COMPLETE',
user: await client.getUser(),
});
}
return token;
},
[client]
);
const getAccessTokenWithPopup = useCallback(
async (
opts?: GetTokenWithPopupOptions,
config?: PopupConfigOptions
): Promise<string | undefined> => {
let token;
try {
token = await client.getTokenWithPopup(opts, config);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'GET_ACCESS_TOKEN_COMPLETE',
user: await client.getUser(),
});
}
return token;
},
[client]
);
const connectAccountWithRedirect = useCallback(
(options: RedirectConnectAccountOptions) =>
client.connectAccountWithRedirect(options),
[client]
);
const getIdTokenClaims = useCallback(
() => client.getIdTokenClaims(),
[client]
);
const loginWithCustomTokenExchange = useCallback(
async (
options: CustomTokenExchangeOptions
): Promise<TokenEndpointResponse> => {
let tokenResponse;
try {
tokenResponse = await client.loginWithCustomTokenExchange(options);
} catch (error) {
throw tokenError(error);
} finally {
// We dispatch the standard GET_ACCESS_TOKEN_COMPLETE action here to maintain
// backward compatibility and consistency with the getAccessTokenSilently flow.
// This ensures the SDK's internal state lifecycle (loading/user updates) remains
// identical regardless of whether the token was retrieved via silent auth or CTE.
dispatch({
type: 'GET_ACCESS_TOKEN_COMPLETE',
user: await client.getUser(),
});
}
return tokenResponse;
},
[client]
);
const exchangeToken = useCallback(
async (
options: CustomTokenExchangeOptions
): Promise<TokenEndpointResponse> => {
return loginWithCustomTokenExchange(options);
},
[loginWithCustomTokenExchange]
);
const handleRedirectCallback = useCallback(
async (
url?: string
): Promise<RedirectLoginResult | ConnectAccountRedirectResult> => {
try {
return await client.handleRedirectCallback(url);
} catch (error) {
throw tokenError(error);
} finally {
dispatch({
type: 'HANDLE_REDIRECT_COMPLETE',
user: await client.getUser(),
});
}
},
[client]
);
const getDpopNonce = useCallback<Auth0Client['getDpopNonce']>(
(id) => client.getDpopNonce(id),
[client]
);
const setDpopNonce = useCallback<Auth0Client['setDpopNonce']>(
(nonce, id) => client.setDpopNonce(nonce, id),
[client]
);
const generateDpopProof = useCallback<Auth0Client['generateDpopProof']>(
(params) => client.generateDpopProof(params),
[client]
);
const createFetcher = useCallback<Auth0Client['createFetcher']>(
(config) => client.createFetcher(config),
[client]
);
const getConfiguration = useCallback<Auth0Client['getConfiguration']>(
() => client.getConfiguration(),
[client]
);
const mfa = useMemo(() => client.mfa, [client]);
const contextValue = useMemo<Auth0ContextInterface<TUser>>(() => {
return {
...state,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithCustomTokenExchange,
exchangeToken,
loginWithRedirect,
loginWithPopup,
connectAccountWithRedirect,
logout,
handleRedirectCallback,
getDpopNonce,
setDpopNonce,
generateDpopProof,
createFetcher,
getConfiguration,
mfa,
};
}, [
state,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithCustomTokenExchange,
exchangeToken,
loginWithRedirect,
loginWithPopup,
connectAccountWithRedirect,
logout,
handleRedirectCallback,
getDpopNonce,
setDpopNonce,
generateDpopProof,
createFetcher,
getConfiguration,
mfa,
]);
return <context.Provider value={contextValue}>{children}</context.Provider>;
};
export default Auth0Provider;