-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathauth0-provider.tsx
204 lines (196 loc) · 6.48 KB
/
auth0-provider.tsx
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
import React, {
PropsWithChildren,
useEffect,
useReducer,
useState,
} from 'react';
import {
Auth0Client,
Auth0ClientOptions,
IdToken,
PopupLoginOptions,
RedirectLoginOptions as Auth0RedirectLoginOptions,
CacheLocation,
} from '@auth0/auth0-spa-js';
import Auth0Context, { RedirectLoginOptions } from './auth0-context';
import {
AppState,
defaultOnRedirectCallback,
loginError,
hasAuthParams,
wrappedGetToken,
} from './utils';
import { reducer } from './reducer';
import { initialAuthState } from './auth-state';
export interface Auth0ProviderOptions extends PropsWithChildren<{}> {
/**
* 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) => void;
/**
* Your Auth0 account domain such as `'example.auth0.com'`,
* `'example.eu.auth0.com'` or , `'example.mycompany.com'`
* (when using [custom domains](https://auth0.com/docs/custom-domains))
*/
domain: string;
/**
* The issuer to be used for validation of JWTs, optionally defaults to the domain above
*/
issuer?: string;
/**
* The Client ID found on your Application settings page
*/
clientId: string;
/**
* The default URL where Auth0 will redirect your browser to with
* the authentication result. It must be whitelisted in
* the "Allowed Callback URLs" field in your Auth0 Application's
* settings. If not provided here, it should be provided in the other
* methods that provide authentication.
*/
redirectUri?: string;
/**
* The value in seconds used to account for clock skew in JWT expirations.
* Typically, this value is no more than a minute or two at maximum.
* Defaults to 60s.
*/
leeway?: number;
/**
* The location to use when storing cache data. Valid values are `memory` or `localstorage`.
* The default setting is `memory`.
*/
cacheLocation?: CacheLocation;
/**
* If true, refresh tokens are used to fetch new access tokens from the Auth0 server. If false, the legacy technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` is used.
* The default setting is `false`.
*
* **Note**: Use of refresh tokens must be enabled by an administrator on your Auth0 client application.
*/
useRefreshTokens?: boolean;
/**
* A maximum number of seconds to wait before declaring background calls to /authorize as failed for timeout
* Defaults to 60s.
*/
authorizeTimeoutInSeconds?: number;
/**
* Changes to recommended defaults, like defaultScope
*/
advancedOptions?: {
/**
* The default scope to be included with all requests.
* If not provided, 'openid profile email' is used. This can be set to `null` in order to effectively remove the default scopes.
*
* Note: The `openid` scope is **always applied** regardless of this setting.
*/
defaultScope?: string;
};
/**
* Maximum allowable elasped time (in seconds) since authentication.
* If the last time the user authenticated is greater than this value,
* the user must be reauthenticated.
*/
maxAge?: string | number;
/**
* The default scope to be used on authentication requests.
* The defaultScope defined in the Auth0Client is included
* along with this scope
*/
scope?: string;
/**
* The default audience to be used for requesting API access.
*/
audience?: string;
/**
* If you need to send custom parameters to the Authorization Server,
* make sure to use the original parameter name.
*/
[key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
}
const toAuth0ClientOptions = (
opts: Auth0ProviderOptions
): Auth0ClientOptions => {
const { clientId, redirectUri, maxAge, ...validOpts } = opts;
return {
...validOpts,
client_id: clientId,
redirect_uri: redirectUri,
max_age: maxAge,
};
};
const toAuth0LoginRedirectOptions = (
opts?: Auth0RedirectLoginOptions
): RedirectLoginOptions | undefined => {
if (!opts) {
return;
}
const { redirectUri, ...validOpts } = opts;
return {
...validOpts,
redirect_uri: redirectUri,
};
};
const Auth0Provider = ({
children,
onRedirectCallback = defaultOnRedirectCallback,
...opts
}: Auth0ProviderOptions): JSX.Element => {
const [client] = useState(() => new Auth0Client(toAuth0ClientOptions(opts)));
const [state, dispatch] = useReducer(reducer, initialAuthState);
useEffect(() => {
(async (): Promise<void> => {
try {
if (hasAuthParams()) {
const { appState } = await client.handleRedirectCallback();
onRedirectCallback(appState);
} else {
await client.getTokenSilently();
}
const isAuthenticated = await client.isAuthenticated();
const user = isAuthenticated && (await client.getUser());
dispatch({ type: 'INITIALISED', isAuthenticated, user });
} catch (error) {
if (error.error !== 'login_required') {
dispatch({ type: 'ERROR', error: loginError(error) });
} else {
dispatch({ type: 'INITIALISED', isAuthenticated: false });
}
}
})();
}, [client, onRedirectCallback]);
const loginWithPopup = async (options?: PopupLoginOptions): Promise<void> => {
dispatch({ type: 'LOGIN_POPUP_STARTED' });
try {
await client.loginWithPopup(options);
} catch (error) {
dispatch({ type: 'ERROR', error: loginError(error) });
return;
}
const isAuthenticated = await client.isAuthenticated();
const user = isAuthenticated && (await client.getUser());
dispatch({ type: 'LOGIN_POPUP_COMPLETE', isAuthenticated, user });
};
return (
<Auth0Context.Provider
value={{
...state,
getAccessTokenSilently: wrappedGetToken((opts?) =>
client.getTokenSilently(opts)
),
getAccessTokenWithPopup: wrappedGetToken((opts?) =>
client.getTokenWithPopup(opts)
),
getIdTokenClaims: (opts): Promise<IdToken> =>
client.getIdTokenClaims(opts),
loginWithRedirect: (opts): Promise<void> =>
client.loginWithRedirect(toAuth0LoginRedirectOptions(opts)),
loginWithPopup: (opts): Promise<void> => loginWithPopup(opts),
logout: (opts): void => client.logout(opts),
}}
>
{children}
</Auth0Context.Provider>
);
};
export default Auth0Provider;