-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathauth0-context.tsx
More file actions
297 lines (277 loc) · 10.1 KB
/
auth0-context.tsx
File metadata and controls
297 lines (277 loc) · 10.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
import {
GetTokenSilentlyOptions,
GetTokenWithPopupOptions,
IdToken,
LogoutOptions as SPALogoutOptions,
PopupLoginOptions,
PopupConfigOptions,
RedirectLoginResult,
User,
GetTokenSilentlyVerboseResponse,
RedirectLoginOptions as SPARedirectLoginOptions,
type Auth0Client,
RedirectConnectAccountOptions,
ConnectAccountRedirectResult,
CustomTokenExchangeOptions,
TokenEndpointResponse
} from '@auth0/auth0-spa-js';
import { createContext } from 'react';
import { AuthState, initialAuthState } from './auth-state';
import { AppState } from './auth0-provider';
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface LogoutOptions extends Omit<SPALogoutOptions, 'onRedirect'> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface RedirectLoginOptions<TAppState = AppState>
extends Omit<SPARedirectLoginOptions<TAppState>, 'onRedirect'> {}
/**
* Contains the authenticated state and authentication methods provided by the `useAuth0` hook.
*/
export interface Auth0ContextInterface<TUser extends User = User>
extends AuthState<TUser> {
/**
* ```js
* const token = await getAccessTokenSilently(options);
* ```
*
* If there's a valid token stored, return it. Otherwise, opens an
* iframe with the `/authorize` URL using the parameters provided
* as arguments. Random and secure `state` and `nonce` parameters
* will be auto-generated. If the response is successful, results
* will be valid according to their expiration times.
*
* If refresh tokens are used, the token endpoint is called directly with the
* 'refresh_token' grant. If no refresh token is available to make this call,
* the SDK will only fall back to using an iframe to the '/authorize' URL if
* the `useRefreshTokensFallback` setting has been set to `true`. By default this
* setting is `false`.
*
* This method may use a web worker to perform the token call if the in-memory
* cache is used.
*
* If an `audience` value is given to this function, the SDK always falls
* back to using an iframe to make the token exchange.
*
* Note that in all cases, falling back to an iframe requires access to
* the `auth0` cookie.
*/
getAccessTokenSilently: {
(
options: GetTokenSilentlyOptions & { detailedResponse: true }
): Promise<GetTokenSilentlyVerboseResponse>;
(options?: GetTokenSilentlyOptions): Promise<string>;
(options: GetTokenSilentlyOptions): Promise<
GetTokenSilentlyVerboseResponse | string
>;
};
/**
* ```js
* const token = await getTokenWithPopup(options, config);
* ```
*
* Get an access token interactively.
*
* Opens a popup with the `/authorize` URL using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated. If the response is successful,
* results will be valid according to their expiration times.
*/
getAccessTokenWithPopup: (
options?: GetTokenWithPopupOptions,
config?: PopupConfigOptions
) => Promise<string | undefined>;
/**
* ```js
* const claims = await getIdTokenClaims();
* ```
*
* Returns all claims from the id_token if available.
*/
getIdTokenClaims: () => Promise<IdToken | undefined>;
/**
* ```js
* const tokenResponse = await exchangeToken({
* subject_token: 'external_token_value',
* subject_token_type: 'urn:acme:legacy-system-token',
* scope: 'openid profile email'
* });
* ```
*
* Exchanges an external subject token for Auth0 tokens via a token exchange request.
*
* This method implements the token exchange grant as specified in RFC 8693.
* It performs a token exchange by sending a request to the `/oauth/token` endpoint
* with the external token and returns Auth0 tokens (access token, ID token, etc.).
*
* The request includes the following parameters:
* - `grant_type`: Hard-coded to "urn:ietf:params:oauth:grant-type:token-exchange"
* - `subject_token`: The external token to be exchanged
* - `subject_token_type`: A namespaced URI identifying the token type (must be under your organization's control)
* - `audience`: The target audience (falls back to the SDK's default audience if not provided)
* - `scope`: Space-separated list of scopes (merged with the SDK's default scopes)
*
* @param options - The options required to perform the token exchange
* @returns A promise that resolves to the token endpoint response containing Auth0 tokens
*/
exchangeToken: (
options: CustomTokenExchangeOptions
) => Promise<TokenEndpointResponse>;
/**
* ```js
* await loginWithRedirect(options);
* ```
*
* Performs a redirect to `/authorize` using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated.
*/
loginWithRedirect: (
options?: RedirectLoginOptions<AppState>
) => Promise<void>;
/**
* ```js
* await loginWithPopup(options, config);
* ```
*
* Opens a popup with the `/authorize` URL using the parameters
* provided as arguments. Random and secure `state` and `nonce`
* parameters will be auto-generated. If the response is successful,
* results will be valid according to their expiration times.
*
* IMPORTANT: This method has to be called from an event handler
* that was started by the user like a button click, for example,
* otherwise the popup will be blocked in most browsers.
*/
loginWithPopup: (
options?: PopupLoginOptions,
config?: PopupConfigOptions
) => Promise<void>;
/**
* ```js
* await connectAccountWithRedirect({
* connection: 'google-oauth2',
* scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/drive.readonly'],
* authorization_params: {
* // additional authorization params to forward to the authorization server
* }
* });
* ```
*
* Redirects to the `/connect` URL using the parameters
* provided as arguments. This then redirects to the connection's login page
* where the user can authenticate and authorize the account to be connected.
*
* If connecting the account is successful `onRedirectCallback` will be called
* with the details of the connected account.
*/
connectAccountWithRedirect: (
options: RedirectConnectAccountOptions
) => Promise<void>;
/**
* ```js
* auth0.logout({ logoutParams: { returnTo: window.location.origin } });
* ```
*
* Clears the application session and performs a redirect to `/v2/logout`, using
* the parameters provided as arguments, to clear the Auth0 session.
* If the `logoutParams.federated` option is specified, it also clears the Identity Provider session.
* [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).
*/
logout: (options?: LogoutOptions) => Promise<void>;
/**
* After the browser redirects back to the callback page,
* call `handleRedirectCallback` to handle success and error
* responses from Auth0. If the response is successful, results
* will be valid according to their expiration times.
*
* @param url The URL to that should be used to retrieve the `state` and `code` values. Defaults to `window.location.href` if not given.
*/
handleRedirectCallback: (url?: string) => Promise<RedirectLoginResult | ConnectAccountRedirectResult>;
/**
* Returns the current DPoP nonce used for making requests to Auth0.
*
* It can return `undefined` because when starting fresh it will not
* be populated until after the first response from the server.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will get the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
getDpopNonce: Auth0Client['getDpopNonce'];
/**
* Sets the current DPoP nonce used for making requests to Auth0.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*
* @param nonce The nonce value.
* @param id The identifier of a nonce: if absent, it will set the nonce
* used for requests to Auth0. Otherwise, it will be used to
* select a specific non-Auth0 nonce.
*/
setDpopNonce: Auth0Client['setDpopNonce'];
/**
* Returns a string to be used to demonstrate possession of the private
* key used to cryptographically bind access tokens with DPoP.
*
* It requires enabling the {@link Auth0ClientOptions.useDpop} option.
*/
generateDpopProof: Auth0Client['generateDpopProof'];
/**
* Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.
* This is a drop-in replacement for the Fetch API's `fetch()` method, but will
* handle certain authentication logic for you, like building the proper auth
* headers or managing DPoP nonces and retries automatically.
*
* Check the `EXAMPLES.md` file for a deeper look into this method.
*/
createFetcher: Auth0Client['createFetcher'];
/**
*
* Returns the Auth0 domain configured in the Auth0Provider.
* **Use Cases:**
* - Advanced integrations requiring the tenant domain
*
* @returns The Auth0 domain (e.g., "tenant.auth0.com")
*/
getDomain: () => string;
/**
* Returns the Auth0 client ID that was configured in the Auth0Provider.
*/
getClientId: () => string;
}
/**
* @ignore
*/
const stub = (): never => {
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
};
/**
* @ignore
*/
export const initialContext = {
...initialAuthState,
buildAuthorizeUrl: stub,
buildLogoutUrl: stub,
getAccessTokenSilently: stub,
getAccessTokenWithPopup: stub,
getIdTokenClaims: stub,
exchangeToken: stub,
loginWithRedirect: stub,
loginWithPopup: stub,
connectAccountWithRedirect: stub,
logout: stub,
handleRedirectCallback: stub,
getDpopNonce: stub,
setDpopNonce: stub,
generateDpopProof: stub,
createFetcher: stub,
getDomain: stub,
getClientId: stub,
};
/**
* The Auth0 Context
*/
const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
export default Auth0Context;