-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathAuth0Context.ts
More file actions
336 lines (310 loc) · 12.1 KB
/
Copy pathAuth0Context.ts
File metadata and controls
336 lines (310 loc) · 12.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
import { createContext } from 'react';
import type {
Credentials,
User,
WebAuthorizeParameters,
ClearSessionParameters,
PasswordRealmParameters,
ExchangeParameters,
CreateUserParameters,
PasswordlessEmailParameters,
LoginEmailParameters,
PasswordlessSmsParameters,
LoginSmsParameters,
MfaChallengeParameters,
LoginOobParameters,
LoginOtpParameters,
LoginRecoveryCodeParameters,
ExchangeNativeSocialParameters,
RevokeOptions,
ResetPasswordParameters,
MfaChallengeResponse,
DPoPHeadersParams,
SessionTransferCredentials,
} from '../types';
import type {
NativeAuthorizeOptions,
NativeClearSessionOptions,
} from '../types/platform-specific';
import type { AuthState } from './reducer';
/**
* The contract for the value provided by the Auth0Context.
* This is the interface that developers will interact with when using the `useAuth0` hook.
*/
export interface Auth0ContextInterface extends AuthState {
/**
* Initiates the web-based authentication flow.
* @param parameters The parameters to send to the `/authorize` endpoint.
* @param options Platform-specific options to customize the authentication experience.
* @returns A promise that resolves with the user's credentials upon successful authentication.
* @throws {AuthError} If the authentication fails.
*/
authorize: (
parameters?: WebAuthorizeParameters,
options?: NativeAuthorizeOptions
) => Promise<Credentials>;
/**
* Clears the user's session and logs them out.
* @param parameters The parameters to send to the `/v2/logout` endpoint.
* @param options Platform-specific options to customize the logout experience.
* @returns A promise that resolves when the session has been cleared.
* @throws {AuthError} If the logout fails.
*/
clearSession: (
parameters?: ClearSessionParameters,
options?: NativeClearSessionOptions
) => Promise<void>;
/**
* Saves the user's credentials.
* @param credentials The credentials to save.
* @returns A promise that resolves when the credentials have been saved.
* @throws {AuthError} If the save fails.
*/
saveCredentials: (credentials: Credentials) => Promise<void>;
/**
* Retrieves the stored credentials, refreshing them if necessary.
* @param scope The scopes to request for the new access token (used during refresh).
* @param minTtl The minimum time-to-live (in seconds) required for the access token.
* @param parameters Additional parameters to send during the refresh request.
* @param forceRefresh If true, forces a refresh of the credentials.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If credentials cannot be retrieved or refreshed.
*/
getCredentials: (
scope?: string,
minTtl?: number,
parameters?: Record<string, unknown>,
forceRefresh?: boolean
) => Promise<Credentials>;
/**
* Clears the user's credentials without clearing their web session and logs them out.
*
* @remarks
* **Platform specific:** This method is only available in the context of a Android/iOS application.
* @returns A promise that resolves when the credentials have been cleared.
*/
clearCredentials: () => Promise<void>;
/**
* Checks if a valid, non-expired set of credentials exists in storage.
* This is a quick, local check and does not perform a network request.
*
* @param minTtl The minimum time-to-live (in seconds) required for the access token to be considered valid. Defaults to 0.
* @returns A promise that resolves with `true` if valid credentials exist, `false` otherwise.
*/
hasValidCredentials: (minTtl?: number) => Promise<boolean>;
/**
* Cancels the ongoing web authentication process.
* This works only on iOS. On other platforms, it will resolve without performing an action.
*/
cancelWebAuth: () => Promise<void>;
/**
* Authenticates a user with their username and password.
* @remarks This method is not supported on the web platform.
* @param parameters The parameters for the password-realm grant.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authentication fails.
*/
loginWithPasswordRealm: (
parameters: PasswordRealmParameters
) => Promise<Credentials>;
/**
* Creates a new user in a database connection.
* @param parameters The parameters for creating the new user.
* @returns A promise that resolves with the new user's profile information.
* @throws {AuthError} If the user creation fails.
*/
createUser: (parameters: CreateUserParameters) => Promise<Partial<User>>;
/**
* Resets the user's password.
* @param parameters The parameters for resetting the password.
* @returns A promise that resolves when the password has been reset.
* @throws {AuthError} If the reset fails.
*/
resetPassword: (parameters: ResetPasswordParameters) => Promise<void>;
/**
* Exchanges an authorization code for tokens.
* This is useful in advanced scenarios where you manage the code flow manually.
* @param parameters The parameters containing the authorization code and verifier.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the exchange fails.
*/
authorizeWithExchange: (
parameters: ExchangeParameters
) => Promise<Credentials>;
/**
* Exchanges an authorization code for native social tokens.
* @param parameters The parameters containing the authorization code and verifier.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the exchange fails.
*/
authorizeWithExchangeNativeSocial: (
parameters: ExchangeNativeSocialParameters
) => Promise<Credentials>;
/**
* Sends a verification code to the user's email.
* @param parameters The parameters for sending the email code.
* @throws {AuthError} If sending the email code fails.
*/
sendEmailCode: (parameters: PasswordlessEmailParameters) => Promise<void>;
/**
* Authorizes a user with their email.
* @param parameters The parameters for email authorization.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authorization fails.
*/
authorizeWithEmail: (
parameters: LoginEmailParameters
) => Promise<Credentials>;
/**
/**
* Sends a verification code to the user's SMS.
* @param parameters The parameters for sending the SMS code.
* @throws {AuthError} If sending the SMS code fails.
*/
sendSMSCode: (parameters: PasswordlessSmsParameters) => Promise<void>;
/**
* Authorizes a user with their SMS.
* @param parameters The parameters for SMS authorization.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authorization fails.
*/
authorizeWithSMS: (parameters: LoginSmsParameters) => Promise<Credentials>;
/**
* Sends a multifactor challenge to the user.
* @param parameters The parameters for the multifactor challenge.
* @returns A promise that resolves when the challenge has been sent.
* @throws {AuthError} If sending the challenge fails.
*/
sendMultifactorChallenge: (
parameters: MfaChallengeParameters
) => Promise<MfaChallengeResponse>;
/**
* Authorizes a user with out-of-band (OOB) authentication.
* @param parameters The parameters for OOB authorization.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authorization fails.
*/
authorizeWithOOB: (parameters: LoginOobParameters) => Promise<Credentials>;
/**
* Authorizes a user with a one-time password (OTP).
* @param parameters The parameters for OTP authorization.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authorization fails.
*/
authorizeWithOTP: (parameters: LoginOtpParameters) => Promise<Credentials>;
/**
* Authorizes a user with a recovery code.
* @param parameters The parameters for recovery code authorization.
* @returns A promise that resolves with the user's credentials.
* @throws {AuthError} If the authorization fails.
*/
authorizeWithRecoveryCode: (
parameters: LoginRecoveryCodeParameters
) => Promise<Credentials>;
// Token Management
revokeRefreshToken: (parameters: RevokeOptions) => Promise<void>;
/**
* Generates DPoP headers for making authenticated requests to custom APIs.
* This method creates the necessary HTTP headers (Authorization and DPoP) to
* securely bind the access token to a specific API request.
*
* @param params Parameters including the URL, HTTP method, access token, and token type.
* @returns A promise that resolves to an object containing the required headers.
*
* @example
* ```typescript
* const credentials = await getCredentials();
*
* if (credentials.tokenType === 'DPoP') {
* const headers = await getDPoPHeaders({
* url: 'https://api.example.com/data',
* method: 'GET',
* accessToken: credentials.accessToken,
* tokenType: credentials.tokenType
* });
*
* const response = await fetch('https://api.example.com/data', { headers });
* }
* ```
*/
getDPoPHeaders: (
params: DPoPHeadersParams
) => Promise<Record<string, string>>;
/**
* Obtains session transfer credentials for performing Native to Web SSO.
*
* @remarks
* This method exchanges the stored refresh token for a session transfer token
* that can be used to authenticate in web contexts without requiring the user
* to log in again. The session transfer token can be passed as a cookie or
* query parameter to the `/authorize` endpoint to establish a web session.
*
* Session transfer tokens are short-lived and expire after a few minutes.
* Once expired, they can no longer be used for web SSO.
*
* If Refresh Token Rotation is enabled, this method will also update the stored
* credentials with new tokens (ID token and refresh token) returned from the
* token exchange.
*
* **Platform specific:** This method is only available on native platforms (iOS/Android).
* On web, it will throw an error.
*
* @param parameters Optional additional parameters to pass to the token exchange.
* @param headers Optional additional headers to include in the token exchange request.
* @returns A promise that resolves with the session transfer credentials.
*
* @example
* ```typescript
* // Get session transfer credentials
* const ssoCredentials = await getSSOCredentials();
*
* // Option 1: Use as a cookie (recommended)
* const cookie = `auth0_session_transfer_token=${ssoCredentials.sessionTransferToken}; path=/; domain=.yourdomain.com; secure; httponly`;
* document.cookie = cookie;
* window.location.href = `https://yourdomain.com/authorize?client_id=${clientId}&...`;
*
* // Option 2: Use as a query parameter
* const authorizeUrl = `https://yourdomain.com/authorize?session_transfer_token=${ssoCredentials.sessionTransferToken}&client_id=${clientId}&...`;
* window.location.href = authorizeUrl;
* ```
*
* @see https://auth0.com/docs/authenticate/login/configure-silent-authentication
*/
getSSOCredentials: (
parameters?: Record<string, any>,
headers?: Record<string, string>
) => Promise<SessionTransferCredentials>;
}
const stub = (): any => {
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
};
const initialContext: Auth0ContextInterface = {
user: null,
error: null,
isLoading: true,
authorize: stub,
clearSession: stub,
saveCredentials: stub,
getCredentials: stub,
clearCredentials: stub,
hasValidCredentials: stub,
loginWithPasswordRealm: stub,
cancelWebAuth: stub,
authorizeWithExchange: stub,
createUser: stub,
authorizeWithRecoveryCode: stub,
authorizeWithExchangeNativeSocial: stub,
sendEmailCode: stub,
sendSMSCode: stub,
authorizeWithEmail: stub,
authorizeWithSMS: stub,
sendMultifactorChallenge: stub,
authorizeWithOOB: stub,
authorizeWithOTP: stub,
resetPassword: stub,
revokeRefreshToken: stub,
getDPoPHeaders: stub,
getSSOCredentials: stub,
};
export const Auth0Context =
createContext<Auth0ContextInterface>(initialContext);