### Start Metro Server for Example App
Source: https://github.com/auth0/react-native-auth0/blob/master/CONTRIBUTING.md
Starts the Metro bundler, which is necessary for running the example application. This command is typically used during development to serve the JavaScript bundle.
```sh
yarn example start
```
--------------------------------
### Run Example App on Android
Source: https://github.com/auth0/react-native-auth0/blob/master/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator. This command is used to test changes made to the library against a real application.
```sh
yarn example android
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/auth0/react-native-auth0/blob/master/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device. This command is used to test changes made to the library against a real application.
```sh
yarn example ios
```
--------------------------------
### Get Credentials with Basic Error Handling
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
A basic example of fetching credentials and logging any encountered errors. This is useful for initial integration.
```javascript
try {
const credentials = await auth0.credentialsManager.getCredentials();
} catch (error) {
console.log(error);
}
```
--------------------------------
### Install Pods After iOS Podfile Update
Source: https://github.com/auth0/react-native-auth0/blob/master/MIGRATION_GUIDE.md
Command to navigate to the iOS directory and install the updated pods after modifying the Podfile.
```bash
cd ios && pod install && cd ..
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/auth0/react-native-auth0/blob/master/CONTRIBUTING.md
Installs all project dependencies using Yarn, essential for setting up the monorepo managed by Yarn workspaces. This command should be run in the root directory of the project.
```sh
yarn
```
--------------------------------
### Android Custom Scheme Callback URL Example
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
An example of an Android custom scheme callback URL with a package name of 'com.example.myapp' and Auth0 domain 'example.us.auth0.com'.
```text
com.example.myapp.auth0://example.us.auth0.com/android/com.example.myapp/callback
```
--------------------------------
### Manage Auth0 SDK Installation
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Commands to check the current version of the Auth0 SDK, update to the latest version, and reinstall iOS pods.
```bash
npm list react-native-auth0
npm install react-native-auth0@latest
cd ios && pod install && cd ..
```
--------------------------------
### Managing Authentication Methods
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Examples demonstrating how to interact with authentication methods, including listing all methods, filtering by type, retrieving a specific method, updating its name, and deleting it.
```APIDOC
## Managing Authentication Methods
### List all methods
```typescript
const methods = await myAccount.getAuthenticationMethods({ accessToken });
```
### List only passkey methods
```typescript
const passkeys = await myAccount.getAuthenticationMethods({
accessToken,
type: AuthenticationMethodTypes.PASSKEY,
});
```
### Get a specific method
```typescript
const method = await myAccount.getAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
});
```
### Update a method name
```typescript
const updated = await myAccount.updateAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
name: 'My Work Phone',
});
```
### Delete a method
```typescript
await myAccount.deleteAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
});
```
```
--------------------------------
### Using Passkeys with Auth0 Class for Signup and Login
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
This example shows how to use the `Auth0` class directly for both passkey signup and login flows. It requires initializing the `Auth0` client with your domain and client ID, and then using `passkeySignupChallenge`, `passkeyLoginChallenge`, and `getTokenByPasskey`. Ensure you have `yourCredentialManagerCreate` and `yourCredentialManagerGet` functions implemented.
```typescript
import Auth0, { PasskeyError } from 'react-native-auth0';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
});
// Signup flow
const signupChallenge = await auth0.passkeySignupChallenge({
email: 'user@example.com',
name: 'John Doe',
realm: 'Username-Password-Authentication',
});
// Use your credential manager library to create the passkey
// signupChallenge.authParamsPublicKey has the WebAuthn creation options
const registrationJson = await yourCredentialManagerCreate(
signupChallenge.authParamsPublicKey
);
const signupCredentials = await auth0.getTokenByPasskey({
authSession: signupChallenge.authSession,
authResponse: registrationJson,
realm: 'Username-Password-Authentication',
});
// Login flow
const loginChallenge = await auth0.passkeyLoginChallenge({
realm: 'Username-Password-Authentication',
});
// Use your credential manager library to assert the passkey
// loginChallenge.authParamsPublicKey has the WebAuthn request options
const assertionJson = await yourCredentialManagerGet(
loginChallenge.authParamsPublicKey
);
const loginCredentials = await auth0.getTokenByPasskey({
authSession: loginChallenge.authSession,
authResponse: assertionJson,
realm: 'Username-Password-Authentication',
});
```
--------------------------------
### Getting Available Factors
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Demonstrates how to retrieve a list of available authentication factor types for the user.
```APIDOC
## Getting Available Factors
```typescript
const factors = await myAccount.getFactors({ accessToken });
// Returns available factor types (e.g., sms, email, totp, push-notification, webauthn-platform)
```
```
--------------------------------
### Sign in with Passkey using useAuth0 Hook
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
This example demonstrates the signin flow using the `useAuth0` hook. It involves fetching a login challenge, asserting an existing passkey via a credential manager, and exchanging the credential for Auth0 tokens. Ensure you have a `yourCredentialManagerGet` function implemented.
```tsx
import { useAuth0, PasskeyError } from 'react-native-auth0';
function PasskeySigninScreen() {
const { passkeyLoginChallenge, getTokenByPasskey } = useAuth0();
const handleSignin = async () => {
try {
// Step 1: Get the login challenge from Auth0
const challenge = await passkeyLoginChallenge({
realm: 'Username-Password-Authentication',
});
// Step 2: Use the platform credential manager to assert an existing passkey
// challenge.authParamsPublicKey contains the WebAuthn PublicKeyCredentialRequestOptions
// Use your preferred library (e.g., react-native-passkey) or native module
const credentialJson = await yourCredentialManagerGet(
challenge.authParamsPublicKey
);
// Step 3: Exchange the credential response for Auth0 tokens
const credentials = await getTokenByPasskey({
authSession: challenge.authSession,
authResponse: credentialJson,
realm: 'Username-Password-Authentication',
audience: 'https://api.example.com',
scope: 'openid profile email offline_access',
});
console.log('Signed in with passkey:', credentials.accessToken);
} catch (error) {
if (error instanceof PasskeyError) {
console.error('Passkey signin failed:', error.type, error.message);
}
}
};
return ;
}
```
--------------------------------
### Example Android Manifest Placeholders with Auth0 Domain
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
An example of configuring manifest placeholders with a specific Auth0 domain. The auth0Scheme uses the applicationId which is auto-replaced at runtime.
```groovy
android {
defaultConfig {
manifestPlaceholders = [auth0Domain: "samples.us.auth0.com", auth0Scheme: "${applicationId}.auth0"]
}
...
}
```
--------------------------------
### Login and Get SSO Credentials with Auth0 Class
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Instantiate the `Auth0` class to manage authentication. Authorize the user with the `offline_access` scope to get a refresh token, then use `credentialsManager.getSSOCredentials()` to obtain the session transfer token. This token can be appended to your web app's URL to initiate SSO.
```js
import Auth0 from 'react-native-auth0';
import { Linking } from 'react-native';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
});
// Login with offline_access scope
await auth0.webAuth.authorize({
scope: 'openid profile email offline_access',
});
// Get session transfer credentials
const ssoCredentials = await auth0.credentialsManager.getSSOCredentials();
console.log('Session Transfer Token:', ssoCredentials.sessionTransferToken);
console.log('Token Type:', ssoCredentials.tokenType);
console.log('Expires In:', ssoCredentials.expiresIn);
// Optional: ID Token and Refresh Token may be returned if RTR is enabled
if (ssoCredentials.idToken) {
console.log('ID Token:', ssoCredentials.idToken);
}
if (ssoCredentials.refreshToken) {
console.log('New Refresh Token received (RTR enabled)');
}
// Open your web application with the session transfer token
const webAppUrl = `https://your-web-app.com/login?session_transfer_token=${ssoCredentials.sessionTransferToken}`;
await Linking.openURL(webAppUrl);
```
--------------------------------
### List and Manage Authentication Methods
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Demonstrates how to retrieve all authentication methods, filter by type (e.g., passkeys), get a specific method by ID, update its name, and delete it. Ensure you have the necessary access token and permissions.
```typescript
import { AuthenticationMethodTypes } from 'react-native-auth0';
// List all methods
const methods = await myAccount.getAuthenticationMethods({ accessToken });
// List only passkey methods
const passkeys = await myAccount.getAuthenticationMethods({
accessToken,
type: AuthenticationMethodTypes.PASSKEY,
});
// Get a specific method
const method = await myAccount.getAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
});
// Update a method name
const updated = await myAccount.updateAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
name: 'My Work Phone',
});
// Delete a method
await myAccount.deleteAuthenticationMethodById({
accessToken,
id: 'authentication-method-id',
});
```
--------------------------------
### Development Build and Testing Commands
Source: https://github.com/auth0/react-native-auth0/blob/master/AGENTS.md
Provides a list of essential commands for developing and testing the React Native Auth0 library. This includes dependency installation, building, cleaning, type checking, running tests, and linting.
```bash
yarn install # Install dependencies
yarn build # Full build (lint + prebuild + bob)
yarn clean # Remove build artifacts
yarn typecheck # TypeScript type checking
```
```bash
yarn test # Run all unit tests
yarn test:ci # Run with coverage
yarn test --watch # Watch mode
```
```bash
yarn lint # Check for issues
yarn lint:fix # Auto-fix issues
```
```bash
yarn example start # Start Metro bundler
yarn example ios # Run iOS example
yarn example android # Run Android example
```
```bash
yarn codegen # Generate native specs from TurboModule definitions
```
--------------------------------
### Initialize Auth0Provider with Domain and Client ID
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Wrap your application with Auth0Provider and provide your Auth0 domain and client ID. This is the primary setup for using the SDK with React Hooks.
```javascript
import { Auth0Provider } from 'react-native-auth0';
const App = () => {
return (
{/* YOUR APP */}
);
};
export default App;
```
--------------------------------
### Configure Biometric Authentication with Auth0Provider
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Set up biometric authentication policies within the Auth0Provider component. This example demonstrates configuring the default policy, but other policies like 'always', 'session', and 'appLifecycle' are commented out for reference.
```jsx
import {
Auth0Provider,
BiometricPolicy,
LocalAuthenticationStrategy,
LocalAuthenticationLevel,
} from 'react-native-auth0';
function App() {
return (
);
}
```
--------------------------------
### Repository Structure of react-native-auth0
Source: https://github.com/auth0/react-native-auth0/blob/master/AGENTS.md
Provides an overview of the directory structure for the react-native-auth0 SDK. It details the location of source code, platform-specific implementations, example applications, and configuration files.
```bash
react-native-auth0/
├── src/ # TypeScript source code
│ ├── index.ts # Public API exports
│ ├── Auth0.ts # Main Auth0 facade class
│ ├── core/ # Platform-agnostic core logic
│ ├── factory/ # Platform client factories
│ ├── platforms/ # Platform-specific implementations
│ ├── hooks/ # React hooks and context
│ ├── specs/ # TurboModule specifications
│ ├── types/ # TypeScript type definitions
│ ├── exports/ # Re-export modules
│ └── plugin/ # Expo config plugin
│
├── ios/ # iOS native code (Swift/ObjC++)
├── android/ # Android native code (Kotlin)
├── example/ # Example application
├── lib/ # Build outputs (generated)
└── [config files] # package.json, tsconfig, etc.
```
--------------------------------
### Exchange External Authentication Provider Token
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
This example shows how to exchange a token obtained from a partner Identity Provider. The `subjectTokenType` should reflect the partner's token type.
```typescript
await customTokenExchange({
subjectToken: externalProviderToken,
subjectTokenType: 'urn:partner:auth-token',
scope: 'openid profile email',
});
```
--------------------------------
### Setup Auth0Provider for React Native Web
Source: https://github.com/auth0/react-native-auth0/blob/master/REACT_NATIVE_WEB_SETUP.md
This snippet demonstrates how to set up the Auth0Provider component in your React Native application when targeting the web platform. It requires your Auth0 domain and client ID. The library automatically handles web-specific implementations.
```jsx
import React from 'react';
import { Auth0Provider } from 'react-native-auth0';
const App = () => (
{/* Your app components */}
);
export default App;
```
--------------------------------
### Get User Info with Access Token
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Retrieve user profile information using an access token. Ensure the token was granted the '/userinfo' audience.
```javascript
auth0.auth
.userInfo({ token: 'the user access_token' })
.then(console.log)
.catch(console.error);
```
--------------------------------
### Login and Get API Credentials with Auth0 Class
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Instantiate the `Auth0` class to log in with `offline_access` scope and manage API credentials. Use `credentialsManager.getApiCredentials` to fetch tokens and `credentialsManager.clearApiCredentials` to remove cached tokens.
```js
import Auth0 from 'react-native-auth0';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
});
// Login with offline_access scope
await auth0.webAuth.authorize({
scope: 'openid profile email offline_access',
audience: 'https://primary-api.example.com',
});
// Get credentials for a specific API
const apiCredentials = await auth0.credentialsManager.getApiCredentials(
'https://first-api.example.com',
'read:data write:data'
);
console.log('Access Token:', apiCredentials.accessToken);
console.log('Token Type:', apiCredentials.tokenType);
console.log('Expires At:', apiCredentials.expiresAt);
console.log('Scope:', apiCredentials.scope);
// Clear cached credentials for a specific API
await auth0.credentialsManager.clearApiCredentials(
'https://first-api.example.com'
);
// Clear with specific scope
await auth0.credentialsManager.clearApiCredentials(
'https://first-api.example.com',
'read:data write:data'
);
```
--------------------------------
### GET /credentials (Web Platform)
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Explains the requirement to pass the audience parameter when calling getCredentials on web platforms to ensure a JWT is returned instead of an opaque token.
```APIDOC
## GET /credentials (Web Platform)
### Description
Retrieves user credentials. On the web platform, the audience parameter must be explicitly passed to this method to ensure the returned access token is a JWT rather than an opaque token.
### Method
GET
### Endpoint
getCredentials(scope, minTtl, options)
### Parameters
#### Path Parameters
- **scope** (string) - Required - The requested scopes (e.g., 'openid profile email').
- **minTtl** (number) - Required - Minimum time-to-live for the token.
#### Request Body
- **options** (object) - Required - Configuration object containing the 'audience' parameter.
### Request Example
{
"audience": "https://your-api.example.com"
}
### Response
#### Success Response (200)
- **accessToken** (string) - The JWT access token.
#### Response Example
{
"accessToken": "eyJhbGciOiJSUzI1Ni..."
}
```
--------------------------------
### Implement LaunchActivity for Android
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Creates a dedicated LaunchActivity that checks if the MainActivity is already running before starting it. This prevents the app from restarting the authentication flow when the app is brought to the foreground.
```java
public class LaunchActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BaseApplication application = (BaseApplication) getApplication();
if (!application.isActivityInBackStack(MainActivity.class)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
finish();
}
}
```
--------------------------------
### Login and Get API Credentials with Hooks
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Use the `useAuth0` hook to log in with the `offline_access` scope and retrieve access tokens for different APIs using the same refresh token. Clear cached credentials for specific APIs or scopes as needed.
```tsx
import { useAuth0 } from 'react-native-auth0';
function MyComponent() {
const { authorize, getApiCredentials, clearApiCredentials } = useAuth0();
const login = async () => {
// Login with offline_access to get a refresh token
await authorize({
scope: 'openid profile email offline_access',
audience: 'https://primary-api.example.com',
});
};
const getFirstApiToken = async () => {
try {
// Get credentials for the first API
const credentials = await getApiCredentials(
'https://first-api.example.com',
'read:data write:data'
);
console.log('First API Access Token:', credentials.accessToken);
console.log('Expires At:', new Date(credentials.expiresAt * 1000));
} catch (error) {
console.error('Error:', error);
}
};
const getSecondApiToken = async () => {
try {
// Get credentials for a different API using the same refresh token
const credentials = await getApiCredentials(
'https://second-api.example.com',
'read:reports'
);
console.log('Second API Access Token:', credentials.accessToken);
} catch (error) {
console.error('Error:', error);
}
};
const clearFirstApiCache = async () => {
// Clear cached credentials for a specific API
await clearApiCredentials('https://first-api.example.com');
// Or clear with specific scope
await clearApiCredentials('https://first-api.example.com', 'read:data');
};
return (
// Your UI components
);
}
```
--------------------------------
### Migrate to DPoP Tokens with React Hooks
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
This hook-based example shows how to check for DPoP token validity within a React component's lifecycle. It manages state to indicate readiness and whether a migration is needed, prompting the user to log in again if an old token is detected.
```javascript
import { useAuth0 } from 'react-native-auth0';
import { useEffect, useState } from 'react';
function App() {
const { authorize, getCredentials, clearSession, hasValidCredentials } =
useAuth0();
const [isReady, setIsReady] = useState(false);
const [needsMigration, setNeedsMigration] = useState(false);
useEffect(() => {
checkAndMigrateToDPoP();
}, []);
const checkAndMigrateToDPoP = async () => {
try {
const hasValid = await hasValidCredentials();
if (!hasValid) {
setIsReady(true);
return;
}
const credentials = await getCredentials();
if (credentials.tokenType !== 'DPoP') {
setNeedsMigration(true);
// Optionally auto-clear or wait for user action
// await clearSession();
// await authorize();
}
setIsReady(true);
} catch (error) {
console.error('Migration check failed:', error);
setIsReady(true);
}
};
const handleMigration = async () => {
try {
await clearSession();
await authorize();
setNeedsMigration(false);
} catch (error) {
console.error('Migration failed:', error);
}
};
if (!isReady) {
return ;
}
if (needsMigration) {
return (
Security Update Required
Please log in again to enhance your account security with DPoP.
);
}
return ;
}
```
--------------------------------
### POST /configuration (DPoP)
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Documentation on how to configure DPoP (Demonstrating Proof-of-Possession) security settings during SDK initialization.
```APIDOC
## POST /configuration (DPoP)
### Description
Configures the Auth0 client instance with DPoP settings. DPoP cryptographically binds tokens to the device.
### Method
POST
### Endpoint
new Auth0({ domain, clientId, useDPoP })
### Parameters
#### Request Body
- **domain** (string) - Required - Your Auth0 domain.
- **clientId** (string) - Required - Your Auth0 client ID.
- **useDPoP** (boolean) - Optional - Enables or disables DPoP (default: true).
### Request Example
{
"domain": "your-domain.auth0.com",
"clientId": "your-client-id",
"useDPoP": true
}
### Response
#### Success Response (200)
- **status** (string) - Configuration applied successfully.
```
--------------------------------
### Configure login vs signup screens with screen_hint
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Illustrates how to use the screen_hint parameter within additionalParameters to direct users specifically to the login or signup pages.
```javascript
const login = async () => {
await authorize({
scope: 'openid profile email',
additionalParameters: {
screen_hint: 'login'
}
});
};
const signup = async () => {
await authorize({
scope: 'openid profile email',
additionalParameters: {
screen_hint: 'signup'
}
});
};
```
--------------------------------
### Get User Profile
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Retrieves the full profile of a specific user using their access token and user ID.
```APIDOC
## Get full user profile
### Description
Retrieves the full profile of a specific user.
### Method
Not explicitly defined, but implies a client-side SDK method call.
### Endpoint
Not applicable (SDK method).
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **id** (string) - Required - The ID of the user to retrieve.
### Request Example
```js
auth0.users('{ACCESS_TOKEN}').getUser({ id: 'user_id' });
```
### Response
#### Success Response
- **user profile** (object) - The full profile of the user.
```
--------------------------------
### Enabling DPoP in Auth0 SDK
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Demonstrates how to initialize the Auth0 SDK with `useDPoP: true` to enable DPoP token support. This is a prerequisite for DPoP migration checks.
```javascript
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
useDPoP: true,
});
const credentials = await auth0.credentialsManager.getCredentials();
if (credentials.tokenType !== 'DPoP') {
}
```
--------------------------------
### Getting new access token with refresh token
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Obtains a new access token using a valid refresh token.
```APIDOC
## Getting new access token with refresh token
### Description
Refreshes an access token using a provided refresh token. This is useful for obtaining a new access token when the current one has expired.
### Method
`auth.refreshToken(options)`
### Parameters
#### Request Body
- **refreshToken** (string) - Required - The user's refresh token.
### Request Example
```js
auth0.auth
.refreshToken({ refreshToken: 'the user refresh_token' })
.then(console.log)
.catch(console.error);
```
```
--------------------------------
### Get user information using user's access_token
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Retrieves user profile information using a valid access token.
```APIDOC
## Get user information using user's access_token
### Description
Fetches the user's profile information by providing an access token. The access token must have been granted the `/userinfo` audience.
### Method
`auth.userInfo(options)`
### Parameters
#### Request Body
- **token** (string) - Required - The user's access token.
### Request Example
```js
auth0.auth
.userInfo({ token: 'the user access_token' })
.then(console.log)
.catch(console.error);
```
```
--------------------------------
### Get New Access Token with Refresh Token
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Obtain a new access token using a user's refresh token.
```javascript
auth0.auth
.refreshToken({ refreshToken: 'the user refresh_token' })
.then(console.log)
.catch(console.error);
```
--------------------------------
### auth.createUser()
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Calls the `/dbconnections/signup` endpoint to create a new user. Works on both native platforms and web.
```APIDOC
## auth.createUser()
### Description
Calls the `/dbconnections/signup` endpoint to create a new user.
### Platform Support
✅ Native, ✅ Web
```
--------------------------------
### Custom Token Exchange with Organization Context
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Perform a custom token exchange while specifying an organization context. This is useful for multi-organization Auth0 setups.
```typescript
const credentials = await customTokenExchange({
subjectToken: 'external-provider-token',
subjectTokenType: 'urn:acme:legacy-system-token',
organization: 'org_123', // or organization name
scope: 'openid profile email',
});
```
--------------------------------
### Initialize Auth0 Client with DPoP Enabled
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Initialize the Auth0 client with DPoP enabled by default or explicitly set `useDPoP: true`. DPoP is enabled by default.
```javascript
import Auth0 from 'react-native-auth0';
// DPoP is enabled by default
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
});
// Or explicitly enable it
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
useDPoP: true, // Explicitly enable DPoP
});
```
--------------------------------
### Debug Platform-Specific Configurations
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Commands to verify package registration on Android and inspect URL schemes on iOS.
```bash
# Android
adb shell dumpsys package your.package.name | grep -A 20 "auth0"
# iOS
plutil -p ios/YourApp/Info.plist | grep -A 5 "CFBundleURLSchemes"
```
--------------------------------
### Get Available Authentication Factors
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Retrieves the types of authentication factors available for the user's account. This helps in understanding which methods can be used for future authentication.
```typescript
const factors = await myAccount.getFactors({ accessToken });
// Returns available factor types (e.g., sms, email, totp, push-notification, webauthn-platform)
```
--------------------------------
### Implement Login with useAuth0 Hook
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Use the `authorize` method from the `useAuth0` hook to initiate the login flow. Handles loading states, user data, and errors.
```javascript
import { useAuth0 } from 'react-native-auth0';
const Component = () => {
const { authorize, user, isLoading, error } = useAuth0();
const login = async () => {
await authorize();
};
if (isLoading) {
return (
SDK is Loading
);
}
return (
{!user && }
{user && Logged in as {user.name}}
{error && {error.message}}
);
};
```
--------------------------------
### Handle Unified AuthError in JavaScript
Source: https://github.com/auth0/react-native-auth0/blob/master/MIGRATION_GUIDE.md
Example of how to catch and handle the standardized AuthError object in JavaScript. This replaces multiple previous error types and provides consistent properties.
```javascript
import { AuthError } from 'react-native-auth0';
catch (e) {
if (e instanceof AuthError) {
console.error(e.name, e.message);
}
}
```
--------------------------------
### Execute SDK Release Process
Source: https://github.com/auth0/react-native-auth0/blob/master/AGENTS.md
Triggers the automated release workflow using release-it. This command handles testing, version bumping, changelog generation, git tagging, npm publishing, and GitHub release creation.
```bash
yarn release
```
--------------------------------
### Get Full User Profile with Management API
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Retrieve a user's complete profile information. Ensure you have a valid access token and the correct user ID.
```javascript
auth0
.users('{ACCESS_TOKEN}')
.getUser({ id: 'user_id' })
.then(console.log)
.catch(console.error);
```
--------------------------------
### Initiate Signup with Bot Protection Verification
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
For signups flagged by Bot Protection, use Universal Login with the 'signup' screen hint to direct users to the signup page. This ensures a smooth verification process.
```javascript
auth0.webAuth.authorize({
connection: realm,
scope: scope,
additionalParameters: {
login_hint: email,
screen_hint: 'signup', // 👈🏻
},
});
```
--------------------------------
### Enroll Passkey
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Enrolls a passkey for the user. This is a three-step process involving requesting a challenge, creating the passkey using the platform's credential manager, and then verifying the enrollment with the returned credential response.
```typescript
import { useAuth0 } from 'react-native-auth0';
import { createPasskey } from './PasskeyModule'; // Your native passkey module
const { myAccount, getApiCredentials } = useAuth0();
// Step 1: Request the enrollment challenge
const accessToken = (await getApiCredentials(`https://${domain}/me/`, scopes))
.accessToken;
const challenge = await myAccount.passkeyEnrollmentChallenge({ accessToken });
// Step 2: Create a passkey using the platform credential manager
const credentialJson = await createPasskey(challenge.authParamsPublicKey);
// Step 3: Verify the enrollment
const method = await myAccount.enrollPasskey({
accessToken,
authenticationMethodId: challenge.authenticationMethodId,
authSession: challenge.authSession,
authResponse: credentialJson,
authParamsPublicKey: challenge.authParamsPublicKey,
});
console.log('Enrolled passkey:', method.id, method.keyId);
```
--------------------------------
### Get Scoped API Credentials
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Obtain an access token with specific My Account API scopes using `getApiCredentials`. Ensure your custom domain is configured and the correct audience is provided.
```typescript
const credentials = await getApiCredentials(
`https://${domain}/me/`,
'read:me:authentication_methods create:me:authentication_methods delete:me:authentication_methods update:me:authentication_methods read:me:factors'
);
const accessToken = credentials.accessToken;
```
--------------------------------
### Configure Local Authentication Options
Source: https://github.com/auth0/react-native-auth0/blob/master/MIGRATION_GUIDE.md
Demonstrates how to define LocalAuthenticationOptions and apply them to the Auth0 constructor or Auth0Provider to enforce biometric or passcode authentication.
```typescript
const localAuthOptions: LocalAuthenticationOptions = {
title: 'Authenticate to retreive your credentials',
subtitle: 'Please authenticate to continue',
description: 'We need to authenticate you to retrieve your credentials',
cancelTitle: 'Cancel',
evaluationPolicy: LocalAuthenticationStrategy.deviceOwnerWithBiometrics,
fallbackTitle: 'Use Passcode',
authenticationLevel: LocalAuthenticationLevel.strong,
deviceCredentialFallback: true,
};
const auth0 = new Auth0({ domain: config.domain, clientId: config.clientId, localAuthenticationOptions: localAuthOptions });
```
```typescript
const App = () => {
return (
{/* YOUR APP */}
);
};
```
--------------------------------
### Accept User Invitations to an Organization
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Handle user invitations by passing the invitation URL to the authorize method. This is useful for onboarding users into organizations via invite links.
```javascript
auth0.webAuth
.authorize({
invitationUrl:
'https://myapp.com/login?invitation=inv123&organization=org123',
})
.then((credentials) => console.log(credentials))
.catch((error) => console.log(error));
```
--------------------------------
### Handle Custom Token Exchange Errors
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Demonstrates how to catch and handle `AuthError` exceptions during the custom token exchange process. It shows how to log the error code and message, and provides an example of handling a specific error like 'invalid_grant'.
```typescript
try {
await auth0.customTokenExchange({...});
} catch (error) {
console.error('Error code:', error.code);
console.error('Error message:', error.message);
// Handle specific errors
if (error.code === 'invalid_grant') {
// Handle invalid token
}
}
```
--------------------------------
### Objective-C AppDelegate URL Handling
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Add this method to your AppDelegate.m file to handle incoming URLs for authentication callbacks.
```objc
#import
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
options:(NSDictionary *)options
{
return [RCTLinkingManager application:app openURL:url options:options];
}
```
--------------------------------
### Initialize Auth0Provider with Custom Headers
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Pass custom headers to Auth0Provider to include them in all API requests. Ensure your domain and client ID are also provided.
```javascript
import { Auth0Provider } from 'react-native-auth0';
const App = () => {
return (
{/* YOUR APP */}
);
};
export default App;
```
--------------------------------
### Instantiate Auth0 Client for Manual Authentication in React Native Web
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES-WEB.md
Creates a singleton instance of the Auth0 client for manual control over authentication flows. This approach is suitable when not using React Hooks or requiring more granular management.
```javascript
// src/api/auth0.ts
import Auth0 from 'react-native-auth0';
import config from '../auth0-configuration';
const auth0 = new Auth0({
domain: config.domain,
clientId: config.clientId,
});
export default auth0;
```
--------------------------------
### Login and Get SSO Credentials with useAuth0 Hook
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Use the `useAuth0` hook to authorize the user with the `offline_access` scope to obtain a refresh token. Then, call `getSSOCredentials` to retrieve the session transfer token and related information. This token can be used to open your web application with a pre-established session.
```tsx
import { useAuth0 } from 'react-native-auth0';
import { Linking } from 'react-native';
function MyComponent() {
const { authorize, getSSOCredentials } = useAuth0();
const login = async () => {
// Login with offline_access to get a refresh token
await authorize({
scope: 'openid profile email offline_access',
});
};
const openWebApp = async () => {
try {
// Get session transfer credentials
const ssoCredentials = await getSSOCredentials();
console.log('Session Transfer Token:', ssoCredentials.sessionTransferToken);
console.log('Token Type:', ssoCredentials.tokenType);
console.log('Expires In:', ssoCredentials.expiresIn, 'seconds');
// Open web app with session transfer token as query parameter
const webAppUrl = `https://your-web-app.com/login?session_transfer_token=${ssoCredentials.sessionTransferToken}`;
await Linking.openURL(webAppUrl);
} catch (error) {
console.error('Failed to get SSO credentials:', error);
}
};
return (
// Your UI components
);
}
```
--------------------------------
### Swift AppDelegate URL Handling
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Add this method to your AppDelegate.swift file to handle incoming URLs for authentication callbacks.
```swift
func application (_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return RCTLinkingManager.application(app, open: url, options: options)
}
```
--------------------------------
### Configure Biometric Authentication with Auth0 Class
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Initialize the Auth0 class with local authentication options, including a specific biometric policy (e.g., BiometricPolicy.session) and timeout. This snippet shows how to retrieve credentials, which will trigger the biometric prompt.
```js
import Auth0, {
BiometricPolicy,
LocalAuthenticationStrategy,
LocalAuthenticationLevel,
} from 'react-native-auth0';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
localAuthenticationOptions: {
title: 'Authenticate to access credentials',
subtitle: 'Please authenticate to continue',
description: 'We need to authenticate you to retrieve your credentials',
cancelTitle: 'Cancel',
evaluationPolicy: LocalAuthenticationStrategy.deviceOwnerWithBiometrics,
fallbackTitle: 'Use Passcode',
authenticationLevel: LocalAuthenticationLevel.strong,
deviceCredentialFallback: true,
biometricPolicy: BiometricPolicy.session,
biometricTimeout: 300, // 5 minutes
},
});
// Get credentials - will prompt for biometric authentication based on policy
const credentials = await auth0.credentialsManager.getCredentials();
```
--------------------------------
### Initialize Auth0Provider for React Native Web
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES-WEB.md
Wraps the application with Auth0Provider to manage authentication state and redirect flows. This is the recommended approach for React Native Web.
```jsx
import React from 'react';
import { Auth0Provider } from 'react-native-auth0';
import config from './auth0-configuration';
import MainComponent from './MainComponent'; // Your main app UI
const App = () => (
);
export default App;
```
--------------------------------
### auth.userInfo()
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Fetches the user's profile from the `/userinfo` endpoint using an access token. Supported on both native platforms and web.
```APIDOC
## auth.userInfo()
### Description
Fetches the user's profile from the `/userinfo` endpoint using an access token.
### Platform Support
✅ Native, ✅ Web
```
--------------------------------
### Build Output Formats
Source: https://github.com/auth0/react-native-auth0/blob/master/AGENTS.md
Describes the different formats and target paths for the library's build outputs, managed by `react-native-builder-bob`. This includes CommonJS, ES Modules, and TypeScript declaration files.
```plaintext
| Target | Path |
| ---------- | ----------------- |
| CommonJS | `lib/commonjs/` |
| ES Modules | `lib/module/` |
| TypeScript | `lib/typescript/` |
```
--------------------------------
### Create User in Database Connection
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Create a new user within a specified database connection, providing email, username, password, and connection name.
```javascript
auth0.auth
.createUser({
email: 'info@auth0.com',
username: 'username',
password: 'password',
connection: 'myconnection',
})
.then(console.log)
.catch(console.error);
```
--------------------------------
### Instantiate Auth0 Class with Custom Headers
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Instantiate the Auth0 class with custom headers for all API requests. This is an alternative to using Auth0Provider with headers.
```javascript
import Auth0 from 'react-native-auth0';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
headers: {
'X-Custom-Header': 'custom-value',
},
});
```
--------------------------------
### Instantiate Auth0 Class
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
If not using React Hooks, instantiate the Auth0 class directly with your domain and client ID. This is an alternative to using the Auth0Provider.
```javascript
import Auth0 from 'react-native-auth0';
const auth0 = new Auth0({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
});
```
--------------------------------
### Android Native Implementation Structure
Source: https://github.com/auth0/react-native-auth0/blob/master/AGENTS.md
Details the directory structure for the Android native implementation of the Auth0 React Native library. It includes the main module, TurboModule spec, package definition, and credential parsing files.
```plaintext
android/src/main/java/com/auth0/react/
├── A0Auth0Module.kt # Main module implementation
├── A0Auth0Spec.kt # TurboModule spec (newarch/)
├── A0Auth0Package.kt # React Native package
├── CredentialsParser.kt # Parse Credentials to JS object
└── ApiCredentialsParser.kt # Parse ApiCredentials to JS object
```
--------------------------------
### iOS Domain Switching Configuration
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Configure iOS's `Info.plist` to support multiple authentication domains by adding custom schemes for each domain to the `CFBundleURLSchemes` array.
```xml
CFBundleURLTypesCFBundleTypeRoleNoneCFBundleURLNameauth0CFBundleURLSchemes$(customScheme1)$(customScheme2)
```
--------------------------------
### Retrieve JWT Access Tokens on Web
Source: https://github.com/auth0/react-native-auth0/blob/master/FAQ.md
Demonstrates how to correctly specify the audience parameter during both login and credential retrieval to ensure a JWT is returned instead of an opaque token on web platforms.
```javascript
import { useAuth0 } from 'react-native-auth0';
const AUDIENCE = 'https://your-api.example.com';
function App() {
const { authorize, getCredentials } = useAuth0();
const onLogin = async () => {
await authorize({
audience: AUDIENCE,
scope: 'openid profile email offline_access',
});
};
const onGetCredentials = async () => {
const credentials = await getCredentials(
'openid profile email offline_access',
0,
{ audience: AUDIENCE }
);
console.log('JWT Access Token:', credentials.accessToken);
};
}
```
```javascript
const AUTH_CONFIG = {
audience: 'https://your-api.example.com',
scope: 'openid profile email offline_access',
};
await authorize(AUTH_CONFIG);
await getCredentials(AUTH_CONFIG.scope, 0, {
audience: AUTH_CONFIG.audience,
});
```
```javascript
const auth0 = new Auth0({
domain: 'YOUR_DOMAIN',
clientId: 'YOUR_CLIENT_ID',
});
await auth0.webAuth.authorize({
audience: 'https://your-api.example.com',
scope: 'openid profile email offline_access',
});
const credentials = await auth0.credentialsManager.getCredentials(
'openid profile email offline_access',
0,
{ audience: 'https://your-api.example.com' }
);
```
--------------------------------
### Passkey Enrollment
Source: https://github.com/auth0/react-native-auth0/blob/master/EXAMPLES.md
Enrolls a new passkey for the user. This is a two-step process involving requesting a challenge and then verifying the credential response.
```APIDOC
## Passkey Enrollment
### Description
Enrolls a new passkey for the user. This is a two-step process involving requesting a challenge and then verifying the credential response.
### Method
`myAccount.passkeyEnrollmentChallenge` (to get challenge) and `myAccount.enrollPasskey` (to verify)
### Parameters
#### Request Body (for `enrollPasskey`)
- **accessToken** (string) - Required - The access token for the authenticated user.
- **authenticationMethodId** (string) - Required - The ID of the authentication method.
- **authSession** (string) - Required - The authentication session identifier.
- **authResponse** (string) - Required - The response from the credential manager.
- **authParamsPublicKey** (string) - Required - Public key parameters for authentication.
### Request Example
```typescript
// Step 1: Request the enrollment challenge
const accessToken = (await getApiCredentials(`https://${domain}/me/`, scopes)).accessToken;
const challenge = await myAccount.passkeyEnrollmentChallenge({ accessToken });
// Step 2: Create a passkey using the platform credential manager
const credentialJson = await createPasskey(challenge.authParamsPublicKey); // Assuming createPasskey is a function you have
// Step 3: Verify the enrollment
const method = await myAccount.enrollPasskey({
accessToken,
authenticationMethodId: challenge.authenticationMethodId,
authSession: challenge.authSession,
authResponse: credentialJson,
authParamsPublicKey: challenge.authParamsPublicKey,
});
console.log('Enrolled passkey:', method.id, method.keyId);
```
### Response
#### Success Response
- **id** (string) - The ID of the newly enrolled passkey.
- **keyId** (string) - The key ID of the enrolled passkey.
```
--------------------------------
### Set iOS Platform Target
Source: https://github.com/auth0/react-native-auth0/blob/master/README.md
Ensure your project's ios/Podfile has the minimum iOS platform target set to 14.0.
```ruby
platform :ios, '14.0'
```