### signup() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Starts a passkey signup flow. Optionally specifies the delivery method for phone verification codes. ```APIDOC ## signup() ### Description Starts a passkey signup flow. Optionally specifies the delivery method for phone verification codes. ### Method Function call ### Parameters - **phoneNumber** (string) - Optional - The phone number for verification. - **deliveryMethod** (string) - Optional - The method to send the code: `'text'` (SMS) or `'voice'`. ### Response #### Success Response Returns an observable that emits the signup result. #### Error Response - **PasskeyVerificationRequiredError** - Contains `verificationRequired` (e.g., `['phone']`). ### Request Example ```ts this.auth.passkey .signup({ phoneNumber: '+14155550100', deliveryMethod: 'voice' }) .subscribe({ error: (err) => { if (err instanceof PasskeyVerificationRequiredError) { // err.verificationRequired, for example ['phone'] } }, }); ``` ``` -------------------------------- ### Install the package from a local .tgz file Source: https://github.com/auth0/auth0-angular/blob/main/CHANGELOG.md Command to install the early access release by downloading the .tgz file from GitHub Releases and running npm install with the path to that file. ```bash npm install /path/to/auth0-auth0-angular-0.1.0.tgz ``` -------------------------------- ### Enable Online Access with Standalone Components (provideAuth0) Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Alternative setup using provideAuth0 with the same configuration for standalone Angular applications. Includes bootstrapApplication and the required providers. ```TypeScript import { bootstrapApplication } from '@angular/platform-browser'; import { provideAuth0, RefreshTokenMode } from '@auth0/auth0-angular'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, { providers: [ provideAuth0({ domain: 'YOUR_AUTH0_DOMAIN', clientId: 'YOUR_AUTH0_CLIENT_ID', useRefreshTokens: true, refreshTokenMode: RefreshTokenMode.Online, useDpop: true, authorizationParams: { redirect_uri: window.location.origin, }, }), ], }); ``` -------------------------------- ### Example: openUrl with Capacitor Browser plugin Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/RedirectLoginOptions.html This example uses the Capacitor Browser plugin to open the login URL in an in-app browser. It requires the @capacitor/browser package and shows the async openUrl signature. ```ts import { Browser } from '@capacitor/browser';const client = new Auth0Client({ async openUrl(url) { await Browser.open({ url }); }}); ``` -------------------------------- ### Install @auth0/auth0-angular with npm Source: https://github.com/auth0/auth0-angular/blob/main/README.md Install the Auth0 Angular SDK using npm. This is the standard installation method for adding the library to an Angular project. ```sh npm install @auth0/auth0-angular ``` -------------------------------- ### Install @auth0/auth0-angular with ng add Source: https://github.com/auth0/auth0-angular/blob/main/README.md Install the Auth0 Angular SDK using the Angular CLI. This also handles configuration or scaffolding steps that might be required. ```sh ng add @auth0/auth0-angular ``` -------------------------------- ### passkey.getLoginChallenge() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Gets a challenge for the WebAuthn login ceremony. Accepts optional realm and organization parameters. ```APIDOC ## passkey.getLoginChallenge() ### Description Gets a challenge for the WebAuthn login ceremony. Accepts optional realm and organization parameters. ### Method getLoginChallenge() ### Parameters #### Optional Parameters - **realm** (string) - Optional - Specify a connection (realm) if your tenant has multiple database connections. - **organization** (string) - Optional - Log in within an organization context. ### Response Returns an Observable that emits a challenge object containing `publicKey` and `authSession`. ### Request Example ```ts this.auth.passkey .getLoginChallenge() .subscribe({ next: (challenge) => console.log(challenge), error: (err) => console.error('Error', err), }); ``` ``` -------------------------------- ### passkey.getSignupChallenge() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Gets a challenge for the WebAuthn signup ceremony. Accepts the same identifier, profile, realm, organization, and deliveryMethod options as signup(). ```APIDOC ## passkey.getSignupChallenge() ### Description Gets a challenge for the WebAuthn signup ceremony. Accepts the same identifier, profile, realm, organization, and deliveryMethod options as signup(). ### Method getSignupChallenge() ### Parameters #### Optional Parameters - **email** (string) - Optional - The user's email address. - **realm** (string) - Optional - Specify a connection (realm) if your tenant has multiple database connections. - **organization** (string) - Optional - Log in within an organization context. - **deliveryMethod** (string) - Optional - The delivery method for verification codes. ### Response Returns an Observable that emits a challenge object containing `publicKey` and `authSession`. ### Request Example ```ts this.auth.passkey .getSignupChallenge({ email: 'user@example.com' }) .subscribe({ next: (challenge) => console.log(challenge), error: (err) => console.error('Error', err), }); ``` ``` -------------------------------- ### Example: openUrl with window.location.replace Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/RedirectLoginOptions.html This example shows how to use the openUrl option to control the redirect by replacing the current URL with the login URL. It is useful when you want to avoid the SDK's default redirect behavior and perform the redirect yourself. ```ts const client = new Auth0Client({ openUrl(url) { window.location.replace(url); }}); ``` -------------------------------- ### Complete Passkey Component Example (signup and login) Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md A standalone Angular component using the AuthService passkey client to handle signup and login. The template shows buttons for unauthenticated users and a welcome message when authenticated. Error handling distinguishes PasskeyRegisterError for registration failures and PasskeyError for other passkey errors. ```TypeScript import { Component, inject } from '@angular/core'; import { AsyncPipe } from '@angular/common'; import { AuthService, PasskeyError, PasskeyRegisterError } from '@auth0/auth0-angular'; @Component({ selector: 'app-passkey-auth', standalone: true, imports: [AsyncPipe], template: `

Welcome, {{ (auth.user$ | async)?.name }}!

`, }) export class PasskeyAuthComponent { auth = inject(AuthService); signup() { this.auth.passkey .signup({ email: 'user@example.com' }) .subscribe({ error: (err) => { if (err instanceof PasskeyRegisterError) { console.error('Registration failed:', err.message); } else if (err instanceof PasskeyError) { console.error('Passkey error:', err.message); } }, }); } login() { this.auth.passkey.login().subscribe({ error: (err) => { if (err instanceof PasskeyError) { console.error('Passkey error:', err.message); } }, }); } } ``` -------------------------------- ### Enroll Passkey using myAccount.enrollmentChallenge and enrollmentVerify Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Works with the Auth0 Angular SDK. Demonstrates the full passkey enrollment flow: starts with enrollmentChallenge, calls navigator.credentials.create in the WebAuthn ceremony, then calls enrollmentVerify with the serialized credential. Note that base64urlToBuffer and serializeCredential are platform-specific helpers you must provide; the SDK handles only the Auth0 challenge and token exchange. ```TypeScript import { switchMap } from 'rxjs'; this.auth.myAccount .enrollmentChallenge({ type: 'passkey' }) .pipe( switchMap(async (challenge) => { // Trigger the browser's WebAuthn credential creation ceremony const credential = await navigator.credentials.create({ publicKey: { ...challenge.authn_params_public_key, challenge: base64urlToBuffer(challenge.authn_params_public_key.challenge), user: { ...challenge.authn_params_public_key.user, id: base64urlToBuffer(challenge.authn_params_public_key.user.id), }, }, }); return this.auth.myAccount.enrollmentVerify({ type: 'passkey', location: challenge.location, auth_session: challenge.auth_session, authn_response: serializeCredential(credential), // serialize to PasskeyCredentialResponse }); }) ) .subscribe({ next: (method) => console.log('Passkey enrolled:', method) }); ``` -------------------------------- ### getSignupChallenge() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Retrieves a signup challenge for passkey creation. Supports specifying a phone delivery method. ```APIDOC ## getSignupChallenge() ### Description Retrieves a signup challenge for passkey creation. Supports specifying a phone delivery method. ### Method Function call ### Parameters - **email** (string) - Optional - The email address for the signup. - **phoneNumber** (string) - Optional - The phone number for verification. - **deliveryMethod** (string) - Optional - The method to send the code: `'text'` (SMS) or `'voice'`. ### Response #### Success Response Returns an observable that emits a challenge object with `publicKey`, `authSession`, and `verificationRequired`. ### Request Example ```ts const challenge = await firstValueFrom(auth.passkey.getSignupChallenge({ email })); ``` ``` -------------------------------- ### Signup with Passkey and Optional scope and audience Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Shows how to pass optional scope and audience to control the access token during passkey signup. ```ts this.auth.passkey .signup({ email: 'user@example.com', scope: 'openid profile email read:orders', audience: 'https://api.example.com', }) .subscribe(); ``` -------------------------------- ### List All Authentication Methods Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Fetches all authentication methods for the current user via `getAuthenticationMethods()`. ```ts this.auth.myAccount.getAuthenticationMethods().subscribe({ next: (methods) => console.log(methods), error: (err) => console.error(err), }); ``` -------------------------------- ### passkey.signup() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Initiates a passkey signup flow. If verification is required, it stops before the passkey prompt and errors with PasskeyVerificationRequiredError, listing the identifiers to verify. ```APIDOC ## passkey.signup() ### Description Initiates a passkey signup flow. If verification is required, it stops before the passkey prompt and errors with PasskeyVerificationRequiredError, listing the identifiers to verify. ### Method signup ### Parameters #### Request Body - **email** (string) - Required - The email address to use for signup ### Response #### Success Response - **isAuthenticated$** - Updates automatically on success - **user$** - Updates automatically on success #### Error Response - **PasskeyVerificationRequiredError** - Thrown when verification is required. Has `verificationRequired` property listing identifiers to verify (e.g., `['email']`) ### Request Example ```ts this.auth.passkey.signup({ email: 'user@example.com' }).subscribe({ error: (err) => { if (err instanceof PasskeyVerificationRequiredError) { // Collect the codes first. The passkey prompt has not been shown yet. this.required = err.verificationRequired; this.codes = {}; } else { console.error('Signup failed', err); } }, }); ``` ``` -------------------------------- ### Native fetch() call before using fetchWithAuth() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Shows the original fetch() call that you would replace with fetchWithAuth(). ```TypeScript const response = await fetch('https://api.example.com/foo', { method: 'GET', headers: { 'user-agent': 'My Client 1.0' }, }); console.log(response.status); console.log(response.headers); console.log(await response.json()); ``` -------------------------------- ### get Source: https://github.com/auth0/auth0-angular/blob/main/docs/classes/AuthClientConfig.html Gets the configuration that has been set by other consumers of the service. ```APIDOC ## get ### Description Gets the configuration that has been set by other consumers of the service. ### Method get ### Returns AuthConfig ``` -------------------------------- ### passkey.login() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Authenticates an existing user with their registered passkey. A single call handles the full assertion flow. ```APIDOC ## passkey.login() ### Description Authenticates an existing user with their registered passkey. A single call handles the full assertion flow. ### Method login() ### Parameters #### Optional Parameters - **realm** (string) - Optional - Specify a connection (realm) if your tenant has multiple database connections. - **organization** (string) - Optional - Log in within an organization context. ### Response Returns an Observable that emits when login is successful. ### Request Example ```ts this.auth.passkey.login().subscribe({ next: () => console.log('Logged in'), error: (err) => console.error('Login failed', err), }); ``` ```ts // Specify a connection (realm) if your tenant has multiple database connections this.auth.passkey.login({ realm: 'Username-Password-Authentication' }).subscribe(); // Log in within an organization context this.auth.passkey.login({ organization: 'org_abc123' }).subscribe(); ``` ``` -------------------------------- ### Login with Invitation and Organization Parameters Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Accept a user invitation by reading the `organization` and `invitation` parameters from the route and passing them to `loginWithRedirect`. ```js import { Component } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { constructor(public auth: AuthService, private activatedRoute: ActivatedRoute) {} loginWithRedirect(): void { const { organization, invitation } = this.activatedRoute.snapshot.params; this.auth.loginWithRedirect({ authorizationParams: { organization, invitation } }); } } ``` -------------------------------- ### Interactive E2E Commands Source: https://github.com/auth0/auth0-angular/blob/main/references/commands.md Interactive E2E workflow: start the local OIDC provider and playground in one terminal, then open the Cypress UI in another. ```bash npm run start:local ``` ```bash npm run e2e ``` -------------------------------- ### enrollmentChallenge Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/MyAccountApiClient.html Starts a challenge for enrolling a new authentication method. ```APIDOC ## enrollmentChallenge ### Description Starts a challenge for enrolling a new authentication method. ### Method enrollmentChallenge ### Parameters - **options** (EnrollmentChallengeOptions) - Required - Options for the enrollment challenge. ### Response Returns a Promise resolving to an EnrollmentChallengeResponse. ``` -------------------------------- ### Using createFetcher() with baseUrl for multiple endpoints Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Configures a fetcher with a baseUrl so you can call different paths on the same API. Absolute URLs ignore the baseUrl. ```TypeScript import { Injectable } from '@angular/core'; import { AuthService, Fetcher } from '@auth0/auth0-angular'; @Injectable({ providedIn: 'root' }) export class ApiService { private fetcher: Fetcher; constructor(private auth: AuthService) { this.fetcher = this.auth.createFetcher({ dpopNonceId: 'my-api', baseUrl: 'https://api.example.com', }); } async getFoo() { return this.fetcher.fetchWithAuth('/foo'); // => https://api.example.com/foo } async getBar() { return this.fetcher.fetchWithAuth('/bar'); // => https://api.example.com/bar } async getXyz() { return this.fetcher.fetchWithAuth('/xyz'); // => https://api.example.com/xyz } async getFromOtherApi() { // If the passed URL is absolute, `baseUrl` will be ignored for convenience: return this.fetcher.fetchWithAuth('https://other-api.example.com/foo'); } } ``` -------------------------------- ### getTokenWithPasskey() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Exchanges a passkey credential for an authentication token. Supports verification codes for signup flows and retryable errors. ```APIDOC ## getTokenWithPasskey() ### Description Exchanges a passkey credential for an authentication token. Supports verification codes for signup flows and retryable errors. ### Method Function call ### Parameters - **authSession** (string) - Required - The authentication session from the signup challenge. - **credential** (PublicKeyCredential) - Required - The passkey credential created by the user. - **verification** (object) - Optional - Verification codes keyed by identifier (e.g., `{ email: '123456' }`). ### Response #### Success Response Returns an observable that emits the authentication result. #### Error Response - **PasskeyGetTokenError** - Retryable if `isRetryable` is true. Contains `authSession` and `verificationRequired` for retry. - **PasskeyError** with code `missing_verification_code` - Retryable; a code was empty. - **MfaRequiredError** - Not retryable; finish with MFA using `error.mfa_token`. - Other errors - Not retryable; start again with `getSignupChallenge()`. ### Request Example ```ts import { AuthService, PasskeyError, PasskeyGetTokenError } from '@auth0/auth0-angular'; import { firstValueFrom } from 'rxjs'; async function granularSignupWithVerification( auth: AuthService, email: string, askUserForCodes: (ids: Array<'email' | 'phone'>) => Promise<{ email?: string; phone?: string }> ) { const challenge = await firstValueFrom(auth.passkey.getSignupChallenge({ email })); let required = challenge.verificationRequired; let verification = required ? await askUserForCodes(required) : undefined; const credential = (await navigator.credentials.create({ publicKey: challenge.publicKey, })) as PublicKeyCredential | null; if (!credential) { throw new Error('Credential creation cancelled'); } let authSession = challenge.authSession; for (;;) { try { return await firstValueFrom( auth.passkey.getTokenWithPasskey({ authSession, credential, verification, }) ); } catch (err) { if (err instanceof PasskeyGetTokenError && err.isRetryable) { authSession = err.authSession!; required = err.verificationRequired!; } else if ( required && err instanceof PasskeyError && err.code === 'missing_verification_code' ) { // A code was empty. Nothing was sent, so the same auth session is still valid } else { throw err; } verification = await askUserForCodes(required); } } } ``` ``` -------------------------------- ### getAuthenticationMethods() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Retrieves all authentication methods for the current user. Optionally filters by type using the `type` parameter. ```APIDOC ## getAuthenticationMethods(type?) ### Description Retrieves all authentication methods for the current user. Optionally filters by type using the `type` parameter. ### Method Observable method on `AuthService.myAccount` ### Endpoint `this.auth.myAccount.getAuthenticationMethods(type?)` ### Parameters #### Query Parameters - **type** (string) - Optional - Filter by authentication method type. Supported values: `'passkey'`, `'password'`, `'phone'`, `'totp'`, `'email'`, `'push-notification'`, `'recovery-code'`, `'webauthn-platform'`, `'webauthn-roaming'`. ### Response #### Success Response - **methods** (array) - List of authentication method objects. ### Request Example ```ts // List all methods this.auth.myAccount.getAuthenticationMethods().subscribe({ next: (methods) => console.log(methods), error: (err) => console.error(err), }); // Filter by type this.auth.myAccount.getAuthenticationMethods('passkey').subscribe({ next: (passkeys) => console.log(passkeys), }); ``` ``` -------------------------------- ### Optional parameters for passkey login() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Optional parameters for `login()`: `realm` for a specific database connection and `organization` for org context. Each call is a separate invocation. ```TypeScript // Specify a connection (realm) if your tenant has multiple database connections this.auth.passkey.login({ realm: 'Username-Password-Authentication' }).subscribe(); ``` ```TypeScript // Log in within an organization context this.auth.passkey.login({ organization: 'org_abc123' }).subscribe(); ``` -------------------------------- ### passkey.continueSignup() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Continues a pending passkey signup with verification codes. The first call shows the passkey prompt. On success, isAuthenticated$ and user$ update automatically. ```APIDOC ## passkey.continueSignup() ### Description Continues a pending passkey signup with verification codes. The first call shows the passkey prompt. On success, isAuthenticated$ and user$ update automatically. ### Method continueSignup ### Parameters #### Request Body - **codes** (object) - Required - Object mapping identifiers to verification codes (e.g., `{ email: '123456' }`) ### Response #### Success Response - **isAuthenticated$** - Updates automatically on success - **user$** - Updates automatically on success #### Error Response - **PasskeyGetTokenError** - Thrown when a code is wrong. Has `isRetryable` property (true if retryable) and `verificationRequired` property listing identifiers needing new codes - **PasskeyError** - Thrown with code `missing_verification_code` when a code is missing or empty, or with code `no_pending_signup` when there is no pending signup ### Request Example ```ts this.auth.passkey.continueSignup(this.codes).subscribe({ next: () => (this.required = []), error: (err) => { if (err instanceof PasskeyError && err.code === 'missing_verification_code') { // A code is empty. Nothing was sent, so keep the form and ask again. return; } if (err instanceof PasskeyGetTokenError && err.isRetryable) { // Wrong code. A retryable error always lists the identifiers that need a new code. this.required = err.verificationRequired!; this.codes = {}; } else { // For example an expired code or session, or no attempts left. Start the signup again. this.required = []; console.error('Verification failed', err); } }, }); ``` ``` -------------------------------- ### Passkey Signup and Login Example Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/PasskeyApiClient.html Shows the high-level usage of the passkey client for signup and login. The signup call takes an object with the user's email; login takes no arguments. Both return a token endpoint response. ```typescript // Signup — single call handles everything const tokens = await auth0.passkey.signup({ email: 'user@example.com' }); // Login — single call handles everything const tokens = await auth0.passkey.login(); ``` -------------------------------- ### Login with Passkey - AuthService.passkey.login() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Single-call passkey authentication for existing users. Subscribes to the returned observable and logs success or error. Requires an Angular component. ```TypeScript import { Component, inject } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-login', template: `` }) export class LoginComponent { private auth = inject(AuthService); login() { this.auth.passkey.login().subscribe({ next: () => console.log('Logged in'), error: (err) => console.error('Login failed', err), }); } } ``` -------------------------------- ### enrollmentChallenge(options: EnrollmentChallengeOptions): Observable Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/ObservableMyAccountApiClient.html Starts enrollment of an authentication method. Returns a challenge response containing `auth_session` and type-specific data. ```APIDOC ## enrollmentChallenge(options: EnrollmentChallengeOptions): Observable ### Description Starts enrollment of an authentication method. Returns a challenge response containing `auth_session` and type-specific data. ### Parameters - **options** (EnrollmentChallengeOptions) - Required - The options for the enrollment challenge. ### Returns Observable ``` -------------------------------- ### Get Authentication Method by ID Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Fetches a specific authentication method using its ID (e.g., 'am_abc123') via `getAuthenticationMethod()`. ```ts this.auth.myAccount.getAuthenticationMethod('am_abc123').subscribe({ next: (method) => console.log(method), }); ``` -------------------------------- ### passkey.getTokenWithPasskey() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Exchanges a WebAuthn credential for tokens. Accepts authSession, credential, and optional realm, organization, scope, audience, and verification parameters. ```APIDOC ## passkey.getTokenWithPasskey() ### Description Exchanges a WebAuthn credential for tokens. Accepts authSession, credential, and optional realm, organization, scope, audience, and verification parameters. ### Method getTokenWithPasskey() ### Parameters #### Required Parameters - **authSession** (string) - Required - The authentication session from the challenge. - **credential** (PublicKeyCredential) - Required - The WebAuthn credential. #### Optional Parameters - **realm** (string) - Optional - Specify a connection (realm) if your tenant has multiple database connections. - **organization** (string) - Optional - Log in within an organization context. - **scope** (string) - Optional - The scope for the tokens. - **audience** (string) - Optional - The audience for the tokens. - **verification** (string) - Optional - Verification data. ### Response Returns an Observable that emits when tokens are obtained. Updates `isAuthenticated$` and `user$`. ### Request Example ```ts this.auth.passkey.getTokenWithPasskey({ authSession: challenge.authSession, credential: credential as PublicKeyCredential, }).subscribe({ next: () => console.log('Tokens obtained'), error: (err) => console.error('Error', err), }); ``` ``` -------------------------------- ### List connected accounts with My Account API Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Retrieve an access token for the My Account API and fetch the connected accounts list. ```ts this.auth .getAccessTokenSilently({ authorizationParams: { audience: `https://YOUR_AUTH0_DOMAIN/me/`, scope: 'read:me:connected_accounts', }, }) .subscribe(async (token) => { const res = await fetch(`https://YOUR_AUTH0_DOMAIN/me/v1/connected-accounts/accounts`, { headers: { Authorization: `Bearer ${token}` }, }); const { accounts } = await res.json(); // accounts contains: id, connection, access_type, scopes, created_at }); ``` -------------------------------- ### Configure AuthModule for Token Vault Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Configure the SDK with an audience, refresh tokens, MRRT, and DPoP to use the Token Vault with the My Account API. ```ts AuthModule.forRoot({ domain: 'YOUR_AUTH0_DOMAIN', clientId: 'YOUR_AUTH0_CLIENT_ID', useRefreshTokens: true, useMrrt: true, useDpop: true, authorizationParams: { redirect_uri: window.location.origin, }, }); ``` -------------------------------- ### Handle connected account details via appState$ Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Subscribe to appState$ to get connected account details after redirect, including connection and timestamps. ```ts ngOnInit() { this.auth.appState$.subscribe((appState) => { if (appState?.connectedAccount) { console.log(`You've connected to ${appState.connectedAccount.connection}`); // Handle the connected account details // appState.connectedAccount contains: id, connection, access_type, created_at, expires_at } }); } ``` -------------------------------- ### getDpopNonce usage example Source: https://github.com/auth0/auth0-angular/blob/main/docs/classes/AuthService.html Gets the DPoP nonce for the specified domain or the default domain. The nonce is used in DPoP proof generation for token binding. ```typescript getDpopNonce(id).subscribe(nonce => ...) ``` -------------------------------- ### Separate fetchers for multiple API endpoints Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Creates a fetcher per API, each with its own dpopNonceId and baseUrl, so each manages its own DPoP nonces independently. ```TypeScript import { Injectable } from '@angular/core'; import { AuthService, Fetcher } from '@auth0/auth0-angular'; @Injectable({ providedIn: 'root' }) export class MultiApiService { private internalApi: Fetcher; private partnerApi: Fetcher; constructor(private auth: AuthService) { // Each fetcher manages its own nonces independently this.internalApi = this.auth.createFetcher({ dpopNonceId: 'internal-api', baseUrl: 'https://internal.example.com', }); this.partnerApi = this.auth.createFetcher({ dpopNonceId: 'partner-api', baseUrl: 'https://partner.example.com', }); } async getInternalData() { const response = await this.internalApi.fetchWithAuth('/data'); return response.json(); } async getPartnerResources() { const response = await this.partnerApi.fetchWithAuth('/resources'); return response.json(); } async getAllData() { const [internal, partner] = await Promise.all([this.getInternalData(), this.getPartnerResources()]); return { internal, partner }; } } ``` -------------------------------- ### Dynamic configuration with provideAppInitializer Source: https://github.com/auth0/auth0-angular/blob/main/docs/index.html Use this snippet to load configuration from an external source before the SDK is instantiated. It uses provideAppInitializer to fetch the config and AuthClientConfig.set to apply it. Note that configuration changes after instantiation have no effect, and the HTTP request must avoid interceptors. ```typescript import { ApplicationConfig, inject, provideAppInitializer } from '@angular/core'; import { provideHttpClient, HttpBackend, HttpClient } from '@angular/common/http'; import { provideAuth0, AuthClientConfig } from '@auth0/auth0-angular'; export function configInitializer(handler: HttpBackend, config: AuthClientConfig) { return () => new HttpClient(handler) .get('/config') .toPromise() .then((loadedConfig: any) => config.set(loadedConfig)); } export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideAuth0(), provideAppInitializer(() => { const handler = inject(HttpBackend); const config = inject(AuthClientConfig); return configInitializer(handler, config)(); }), ], }; ``` -------------------------------- ### Using auth0.connectAccountWithRedirect to get ConnectAccountRedirectResult Source: https://github.com/auth0/auth0-angular/blob/main/docs/types/ConnectAccountRedirectResult.html Example of using the auth0.connectAccountWithRedirect method to obtain the ConnectAccountRedirectResult. It shows how to access appState, connection, and response_type from the result. The response_type is expected to be 'connect_code'. ```typescript const result = await auth0.connectAccountWithRedirect(options); console.log(result.appState); // Access persisted app state console.log(result.connection); // The connection of the account you connected to. console.log(result.response_type === 'connect_code'); // The response type will be 'connect_code' ``` -------------------------------- ### getAccessTokenWithPopup usage example Source: https://github.com/auth0/auth0-angular/blob/main/docs/classes/AuthService.html Get an access token interactively. Opens a popup with the `/authorize` URL using the provided options; `state` and `nonce` are auto-generated. Results are valid until expiration. ```typescript getTokenWithPopup(options).subscribe(token => ...) ``` -------------------------------- ### Replacing fetch() with fetchWithAuth() in a component Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Shows the updated code using fetchWithAuth() inside a component. Requires dpopNonceId in createFetcher() parameters when DPoP is enabled. ```TypeScript import { Component } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-data', template: `...`, }) export class DataComponent { constructor(private auth: AuthService) {} async fetchData() { const fetcher = this.auth.createFetcher({ dpopNonceId: 'my_api_request', }); const response = await fetcher.fetchWithAuth('https://api.example.com/foo', { method: 'GET', headers: { 'user-agent': 'My Client 1.0' }, }); console.log(response.status); console.log(response.headers); console.log(await response.json()); } } ``` -------------------------------- ### Get current user profile Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Retrieves the current user's profile. Requires the `read:me:profile` scope. Logs the profile's given name and email, or an error if the request fails. ```TypeScript this.auth.myAccount.getUserProfile().subscribe({ next: (profile) => console.log(profile.given_name, profile.email), error: (err) => console.error(err), }); ``` -------------------------------- ### constructor Source: https://github.com/auth0/auth0-angular/blob/main/docs/classes/AuthClientConfig.html Creates a new instance of AuthClientConfig with an optional initial configuration. ```APIDOC ## constructor ### Description Creates a new instance of AuthClientConfig with an optional initial configuration. ### Method constructor ### Parameters - `config` (AuthConfig) - Optional - The initial configuration. ### Returns AuthClientConfig ``` -------------------------------- ### Retrieve user profile with user$ observable Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Access the `user$` observable on `AuthService` to get the user profile. It automatically reacts to the `isAuthenticated$` state, so no extra authentication check is needed. The component exposes `user$` to the template. ```TypeScript import { Component } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-profile', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class ProfileComponent { user$ = this.auth.user$; constructor(public auth: AuthService) {} } ``` -------------------------------- ### All Supported Passkey Signup Properties Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Lists all supported properties for passkey signup, including optional identifiers, profile fields, connection, organization, delivery method, and token options. ```ts this.auth.passkey .signup({ // At least one identifier is typically required email: 'user@example.com', phoneNumber: '+1234567890', // optional, E.164 format username: 'janedoe', // optional // Profile fields (all optional) name: 'Jane Doe', givenName: 'Jane', familyName: 'Doe', nickname: 'janie', picture: 'https://example.com/avatar.png', userMetadata: { plan: 'pro' }, // Connection and org realm: 'my-db-connection', organization: 'org_abc123', // Phone OTP channel for identifier verification: 'text' (SMS) or 'voice' deliveryMethod: 'text', // Token options scope: 'openid profile email', audience: 'https://api.example.com', }) .subscribe(); ``` -------------------------------- ### Configure Auth0 with Refresh Tokens for Passkeys Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Required setup for passkey usage: must set useRefreshTokens: true because passkey authentication does not create an Auth0 session cookie. Without refresh tokens, getAccessTokenSilently() may fail with login_required or return tokens for a different user. Configure in app.config.ts (standalone). ```ts // app.config.ts (standalone) import { provideAuth0 } from '@auth0/auth0-angular'; export const appConfig: ApplicationConfig = { providers: [ provideAuth0({ domain: 'YOUR_AUTH0_DOMAIN', clientId: 'YOUR_AUTH0_CLIENT_ID', useRefreshTokens: true, // Required for passkey-based sessions authorizationParams: { redirect_uri: window.location.origin, }, }), ], }; ``` -------------------------------- ### Signup with Passkey using AuthService.passkey.signup() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Registers a new user with a passkey. Inject AuthService and call passkey.signup(). The Observable completes with the token response, and isAuthenticated$ and user$ update automatically. ```ts import { Component, inject } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-signup', template: `` }) export class SignupComponent { private auth = inject(AuthService); signup() { this.auth.passkey .signup({ email: 'user@example.com', name: 'Jane Doe' }) .subscribe({ next: (tokens) => console.log('Signed up, access token:', tokens.access_token), error: (err) => console.error('Signup failed', err), }); } } ``` -------------------------------- ### Build, test, and lint commands Source: https://github.com/auth0/auth0-angular/blob/main/CLAUDE.md The build command compiles the library for production. The test:ci command runs unit tests with coverage and requires no credentials Passthrough. The lint command runs ESLint via ng lint. ```bash npm run build # Build the library (production) npm run test:ci # Unit tests with coverage (CI; no credentials required) npm run lint # ESLint via ng lint ``` -------------------------------- ### HttpMethod.Get Source: https://github.com/auth0/auth0-angular/blob/main/docs/enums/HttpMethod.html The Get member of the HttpMethod enumeration, representing the HTTP GET method. ```APIDOC ## HttpMethod.Get ### Description The Get member of the HttpMethod enumeration, representing the HTTP GET method. ### Enumeration Member Get: "GET" ### Value "GET" ``` -------------------------------- ### signup(options: PasskeySignupOptions): Promise Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/PasskeyApiClient.html Register a new user with a passkey. Handles the full flow: requests a signup challenge, triggers the browser WebAuthn credential creation ceremony, serializes the result, and exchanges it for tokens. ```APIDOC ## signup(options: PasskeySignupOptions): Promise ### Description Register a new user with a passkey. Handles the full flow: requests a signup challenge, triggers the browser WebAuthn credential creation ceremony, serializes the result, and exchanges it for tokens. If the server requires identifier verification, it stops before creating the passkey and throws `PasskeyVerificationRequiredError`. Collect the OTP codes and call `continueSignup()` to finish. ### Parameters - **options** (PasskeySignupOptions) - Required - Passkey signup options (user identifier, optional scope/audience) ### Returns Promise - A promise that resolves to the token endpoint response containing access/ID tokens ### Throws - If WebAuthn is not supported in the browser - If the challenge request fails - If OTP codes are needed before the passkey is created - If the token exchange fails - If the user cancels the WebAuthn prompt ``` -------------------------------- ### Granular Passkey APIs - signup() and login() with getSignupChallenge/getLoginChallenge and getTokenWithPasskey() Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Manual WebAuthn ceremony for signup and login. Assumes identifier verification is off; if verification is on, `getSignupChallenge()` returns `verificationRequired` and OTP must be collected before the passkey prompt. `getTokenWithPasskey()` updates auth state. ```TypeScript import { Component, inject } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; import { from, throwError } from 'rxjs'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-granular-passkey', template: ` `, }) export class GranularPasskeyComponent { private auth = inject(AuthService); signup() { // Assumes identifier verification is off (no challenge.verificationRequired) this.auth.passkey .getSignupChallenge({ email: 'user@example.com' }) .pipe( switchMap((challenge) => from(navigator.credentials.create({ publicKey: challenge.publicKey })).pipe( switchMap((credential) => credential ? this.auth.passkey.getTokenWithPasskey({ authSession: challenge.authSession, credential: credential as PublicKeyCredential, }) : throwError(() => new Error('Credential creation cancelled')) ) ) ) ) .subscribe({ next: () => console.log('Signed up'), error: (err) => console.error('Signup failed', err), }); } login() { this.auth.passkey .getLoginChallenge() .pipe( switchMap((challenge) => from(navigator.credentials.get({ publicKey: challenge.publicKey })).pipe( switchMap((credential) => credential ? this.auth.passkey.getTokenWithPasskey({ authSession: challenge.authSession, credential: credential as PublicKeyCredential, }) : throwError(() => new Error('Credential request cancelled')) ) ) ) ) .subscribe({ next: () => console.log('Logged in'), error: (err) => console.error('Login failed', err), }); } } ``` -------------------------------- ### Dynamic configuration of Auth0 Angular SDK using provideAppInitializer and APP_INITIALIZER Source: https://github.com/auth0/auth0-angular/blob/main/README.md These are the two ways to load dynamic configuration from an external source before the Auth0 SDK is instantiated. The standalone approach uses provideAppInitializer with HttpClient created from HttpBackend to avoid interceptors. The NgModule approach uses APP_INITIALIZER with a factory. The configuration is set via AuthClientConfig.set and cannot be updated later. ```ts import { ApplicationConfig, inject, provideAppInitializer } from '@angular/core'; import { provideHttpClient, HttpBackend, HttpClient } from '@angular/common/http'; import { provideAuth0, AuthClientConfig } from '@auth0/auth0-angular'; export function configInitializer(handler: HttpBackend, config: AuthClientConfig) { return () => new HttpClient(handler) .get('/config') .toPromise() .then((loadedConfig: any) => config.set(loadedConfig)); } export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideAuth0(), provideAppInitializer(() => { const handler = inject(HttpBackend); const config = inject(AuthClientConfig); return configInitializer(handler, config)(); }), ], }; ``` ```ts import { APP_INITIALIZER } from '@angular/core'; import { HttpClientModule, HttpClient, HttpBackend } from '@angular/common/http'; import { AuthModule, AuthClientConfig } from '@auth0/auth0-angular'; function configInitializer(handler: HttpBackend, config: AuthClientConfig) { return () => new HttpClient(handler) .get('/config') .toPromise() .then((loadedConfig: any) => config.set(loadedConfig)); } @NgModule({ imports: [HttpClientModule, AuthModule.forRoot()], providers: [ { provide: APP_INITIALIZER, useFactory: configInitializer, deps: [HttpBackend, AuthClientConfig], multi: true, }, ], }) export class AppModule {} ``` -------------------------------- ### signup Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/PasskeyApiClient.html Registers a new user with a passkey. This method handles the full flow: challenge, WebAuthn, and token exchange. ```APIDOC ## signup(options: PasskeySignupOptions): Promise ### Description Registers a new user with a passkey. This method handles the full flow: challenge, WebAuthn, and token exchange. ### Method signup ### Parameters - **options** (PasskeySignupOptions) - Required - Options for the signup operation. ### Response Returns a Promise that resolves to a TokenEndpointResponse. ### Example ```typescript const tokens = await auth0.passkey.signup({ email: 'user@example.com' }); ``` ``` -------------------------------- ### getFactors Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/MyAccountApiClient.html Get the status of all factors for the current user. ```APIDOC ## getFactors(): Promise ``` -------------------------------- ### Format Command Source: https://github.com/auth0/auth0-angular/blob/main/references/commands.md Runs Prettier manually. Prettier also runs automatically via the pre-commit hook (`pretty-quick --staged`). ```bash npx pretty-quick ``` -------------------------------- ### API Docs Command Source: https://github.com/auth0/auth0-angular/blob/main/references/commands.md Generates TypeDoc API documentation output. ```bash npm run docs ``` -------------------------------- ### getAuthenticationMethods Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/MyAccountApiClient.html Get a list of all authentication methods for the current user. Optionally filter by type. ```APIDOC ## getAuthenticationMethods(type?: AuthenticationMethodType): Promise ``` -------------------------------- ### v2: loginWithRedirect with openUrl Source: https://github.com/auth0/auth0-angular/blob/main/MIGRATION_GUIDE.md Shows the v2 replacement for redirectMethod: implement openUrl to handle the redirect to Auth0 instead of using window.location.assign. ```ts this.auth.loginWithRedirect({ openUrl: (url) => { // Open url in the browser } }); ``` -------------------------------- ### Run Cypress e2e tests with npm run e2e:ci Source: https://github.com/auth0/auth0-angular/blob/main/references/testing.md Runs the Cypress end-to-end tests against the local OIDC provider and playground, then runs Cypress headless. Default credentials are `testing` / `testing`. ```bash npm run e2e:ci # Starts local OIDC + playground, then Cypress headless ``` -------------------------------- ### getAuthenticators Source: https://github.com/auth0/auth0-angular/blob/main/EXAMPLES.md Retrieves the list of authenticators enrolled for the user. Useful for selecting an authenticator to challenge. ```APIDOC ## getAuthenticators ### Description Retrieves the list of authenticators enrolled for the user. Useful for selecting an authenticator to challenge. ### Method `getAuthenticators` ### Parameters - **mfaToken** (string) - Required - The MFA token obtained during authentication. ### Response Returns an Observable that emits an array of authenticator objects, each with an `id` property. ### Request Example ```ts this.auth.mfa.getAuthenticators(mfaToken).subscribe((authenticators) => { console.log(authenticators[0].id); }); ``` ``` -------------------------------- ### getSignupChallenge Source: https://github.com/auth0/auth0-angular/blob/main/docs/interfaces/PasskeyApiClient.html Retrieves a signup challenge for passkey registration. ```APIDOC ## getSignupChallenge(options: PasskeySignupChallengeOptions): Promise ### Description Retrieves a signup challenge for passkey registration. ### Method getSignupChallenge ### Parameters - **options** (PasskeySignupChallengeOptions) - Required - Options for the signup challenge. ### Response Returns a Promise that resolves to a PasskeySignupChallenge. ``` -------------------------------- ### Lint Command Source: https://github.com/auth0/auth0-angular/blob/main/references/commands.md Runs the linter. ```bash npm run lint ```