# Authentication API

The Authentication API provides access to Auth0's authentication flows, token management, and user authentication operations. It includes support for OAuth 2.0, OpenID Connect, passwordless authentication, and CIBA (Client Initiated Backchannel Authentication).

## Capabilities

### OAuth Operations

OAuth 2.0 and OpenID Connect authentication flows for token exchange and user authentication.

```typescript { .api }
class OAuth {
  constructor(options: AuthenticationClientOptions);
  
  authorizationCodeGrant(
    options: AuthorizationCodeGrantRequest,
    grantOptions?: AuthorizationCodeGrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  authorizationCodeGrantWithPKCE(
    options: AuthorizationCodeWithPKCEGrantRequest,
    grantOptions?: AuthorizationCodeGrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  clientCredentialsGrant(
    options: ClientCredentialsGrantRequest,
    grantOptions?: GrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  passwordGrant(
    options: PasswordGrantRequest,
    grantOptions?: GrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  refreshTokenGrant(
    options: RefreshTokenGrantRequest,
    grantOptions?: GrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  revokeRefreshToken(
    options: RevokeRefreshTokenRequest,
    initOverrides?: InitOverride
  ): Promise<VoidApiResponse>;
  
  pushedAuthorization(
    options: PushedAuthorizationRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<PushedAuthorizationResponse>>;
}
```

**Usage Examples:**

```typescript
import { AuthenticationClient } from "auth0";

const auth = new AuthenticationClient({
  domain: "your-domain.auth0.com",
  clientId: "your-client-id",
  clientSecret: "your-client-secret"
});

// Authorization Code Grant
const tokens = await auth.oauth.authorizationCodeGrant({
  code: "authorization_code",
  redirect_uri: "https://yourapp.com/callback"
});

// Client Credentials Grant
const clientTokens = await auth.oauth.clientCredentialsGrant({
  audience: "https://your-api.com"
});

// Refresh Token
const refreshedTokens = await auth.oauth.refreshTokenGrant({
  refresh_token: "refresh_token_here"
});
```

### Additional OAuth Grant Types

The OAuth client supports additional grant types for specialized use cases:

```typescript { .api }
class OAuth {
  // Device Code Flow
  deviceCodeGrant(
    options: DeviceCodeGrantRequest,
    grantOptions?: GrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  // Token Exchange Flow
  tokenExchangeGrant(
    options: TokenExchangeGrantRequest,
    grantOptions?: GrantOptions
  ): Promise<JSONApiResponse<TokenSet>>;
  
  // Federated Connection Token Exchange
  tokenForConnection(
    options: TokenForConnectionRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<TokenForConnectionResponse>>;
}
```

### OAuth Grant Request Interfaces

Complete interface definitions for OAuth grant requests:

```typescript { .api }
interface DeviceCodeGrantRequest {
  client_id?: string;
  device_code: string;
}

interface TokenExchangeGrantRequest {
  client_id?: string;
  subject_token: string;
  audience?: string;
  scope?: string;
  user_profile: string;
}

interface TokenForConnectionRequest {
  subject_token: string;
  connection: string;
  login_hint?: string;
}

interface TokenForConnectionResponse {
  access_token: string;
  scope?: string;
  expires_at: number;
  connection: string;
  [key: string]: unknown;
}
```

### OAuth Constants

Constants used for OAuth flows:

```typescript { .api }
declare const TOKEN_FOR_CONNECTION_GRANT_TYPE: 'urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token';
declare const TOKEN_FOR_CONNECTION_TOKEN_TYPE: 'urn:ietf:params:oauth:token-type:refresh_token';
declare const TOKEN_FOR_CONNECTION_REQUESTED_TOKEN_TYPE: 'http://auth0.com/oauth/token-type/federated-connection-access-token';
declare const TOKEN_URL: '/oauth/token';
```

### Database Operations

User registration and password management for Auth0 database connections.

```typescript { .api }
class Database {
  constructor(options: AuthenticationClientOptions);
  
  signUp(
    options: SignUpRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<SignUpResponse>>;
  
  changePassword(
    options: ChangePasswordRequest,
    initOverrides?: InitOverride
  ): Promise<TextApiResponse>;
}
```

**Usage Examples:**

```typescript
// User Registration
const newUser = await auth.database.signUp({
  email: "user@example.com",
  password: "securePassword123",
  connection: "Username-Password-Authentication",
  username: "newuser",
  given_name: "John",
  family_name: "Doe"
});

// Password Change Request
await auth.database.changePassword({
  email: "user@example.com",
  connection: "Username-Password-Authentication"
});
```

### Passwordless Authentication

Email and SMS-based passwordless authentication flows.

```typescript { .api }
class Passwordless {
  constructor(options: AuthenticationClientOptions);
  
  sendEmail(
    options: PasswordlessEmailRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<PasswordlessResponse>>;
  
  sendSMS(
    options: PasswordlessSMSRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<PasswordlessResponse>>;
  
  loginWithEmail(
    options: PasswordlessEmailLoginRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<TokenSet>>;
  
  loginWithSMS(
    options: PasswordlessSMSLoginRequest,
    initOverrides?: InitOverride
  ): Promise<JSONApiResponse<TokenSet>>;
}
```

**Usage Examples:**

```typescript
// Send passwordless email
await auth.passwordless.sendEmail({
  email: "user@example.com",
  send: "link", // or "code"
  auth_params: {
    scope: "openid profile email"
  }
});

// Login with email code/link
const tokens = await auth.passwordless.loginWithEmail({
  email: "user@example.com",
  code: "123456" // if using code
});
```

### Backchannel Authentication (CIBA)

Client Initiated Backchannel Authentication (CIBA) enables decoupled authentication flows where the user logs in on a separate "Authorization Device" from the "Consumption Device" that receives tokens.

```typescript { .api }
interface IBackchannel {
  authorize(options: AuthorizeOptions): Promise<AuthorizeResponse>;
  backchannelGrant(options: TokenOptions): Promise<TokenResponse>;
}

class Backchannel extends BaseAuthAPI implements IBackchannel {
  constructor(options: AuthenticationClientOptions);
  
  authorize(options: AuthorizeOptions): Promise<AuthorizeResponse>;
  backchannelGrant(options: TokenOptions): Promise<TokenResponse>;
}
```

**CIBA Types and Interfaces:**

```typescript { .api }
interface AuthorizeOptions {
  binding_message: string;
  scope: string;
  audience?: string;
  request_expiry?: string;
  userId: string;
  subjectIssuerContext?: string;
  authorization_details?: string;
  [key: string]: string;
}

interface AuthorizeResponse {
  auth_req_id: string;
  expires_in: number;
  interval: number;
}

interface TokenOptions {
  auth_req_id: string;
}

interface TokenResponse {
  access_token: string;
  refresh_token?: string;
  id_token: string;
  token_type?: string;
  expires_in: number;
  scope: string;
  authorization_details?: string;
}
```

**Usage Examples:**

```typescript
// Step 1: Initiate backchannel authorization
const authResponse = await auth.backchannel.authorize({
  userId: "auth0|507f1f77bcf86cd799439011",
  binding_message: "Please confirm this login on your mobile device",
  scope: "openid profile email",
  audience: "https://your-api.com"
});

// Step 2: Poll for token (after user confirms on their device)
const tokenResponse = await auth.backchannel.backchannelGrant({
  auth_req_id: authResponse.auth_req_id
});
```

### Token Exchange

RFC 8693-compliant custom token exchange operations for external identity provider migrations and token exchange scenarios.

```typescript { .api }
interface ICustomTokenExchange {
  exchangeToken(options: CustomTokenExchangeOptions): Promise<TokenResponse>;
}

class CustomTokenExchange extends BaseAuthAPI implements ICustomTokenExchange {
  constructor(options: AuthenticationClientOptions);
  
  exchangeToken(options: CustomTokenExchangeOptions): Promise<TokenResponse>;
}
```

**Token Exchange Types and Interfaces:**

```typescript { .api }
interface CustomTokenExchangeOptions {
  /** The type identifier for the subject token being exchanged */
  subject_token_type: string;
  /** The opaque token value being exchanged for Auth0 tokens */
  subject_token: string;
  /** The target audience for the requested Auth0 token */
  audience: string;
  /** Space-separated list of OAuth 2.0 scopes being requested */
  scope?: string;
  /** Additional custom parameters for Auth0 Action processing */
  [key: string]: unknown;
}

interface TokenResponse {
  /** Bearer token for API authorization */
  access_token: string;
  /** Refresh token (requires `offline_access` scope) */
  refresh_token?: string;
  /** JWT containing user identity claims */
  id_token: string;
  /** Typically "Bearer" */
  token_type?: string;
  /** Token validity in seconds (default: 86400) */
  expires_in: number;
  /** Granted permissions space */
  scope: string;
}
```

**Usage Examples:**

```typescript
// External IdP migration scenario
const tokens = await auth.tokenExchange.exchangeToken({
  subject_token_type: 'urn:external-idp:legacy',
  subject_token: externalIdPToken,
  audience: 'https://api.your-service.com',
  scope: 'openid profile email'
});

// Access the exchanged tokens
console.log('Access Token:', tokens.access_token);
console.log('ID Token:', tokens.id_token);
```

**Security Considerations:**

- **subject_token_type** must be a namespaced URI under your organization's control
- Forbidden patterns: `^urn:ietf:params:oauth:*`, `^https://auth0.com/*`, `^urn:auth0:*`
- Subject tokens must be validated in Auth0 Actions using strong cryptographic verification
- Implement replay attack protection
- Store tokens in secure, encrypted storage

## Request Types

### OAuth Grant Types

```typescript { .api }
interface AuthorizationCodeGrantRequest extends ClientCredentials {
  code: string;
  redirect_uri?: string;
}

interface AuthorizationCodeWithPKCEGrantRequest extends ClientCredentials {
  code: string;
  code_verifier: string;
  redirect_uri?: string;
}

interface ClientCredentialsGrantRequest extends ClientCredentials {
  audience: string;
  organization?: string;
}

interface PasswordGrantRequest extends ClientCredentials {
  audience?: string;
  username: string;
  password: string;
  scope?: string;
  realm?: string;
}

interface RefreshTokenGrantRequest extends ClientCredentials {
  refresh_token: string;
  scope?: string;
}

interface RevokeRefreshTokenRequest extends ClientCredentials {
  token: string;
}
```

### Database Request Types

```typescript { .api }
interface SignUpRequest {
  client_id?: string;
  email: string;
  password: string;
  connection: string;
  username?: string;
  given_name?: string;
  family_name?: string;
  name?: string;
  nickname?: string;
  picture?: string;
  user_metadata?: { [key: string]: unknown };
}

interface ChangePasswordRequest {
  client_id?: string;
  email: string;
  connection: string;
}
```

### Passwordless Request Types

```typescript { .api }
interface PasswordlessEmailRequest {
  client_id?: string;
  email: string;
  send: 'link' | 'code';
  auth_params?: { [key: string]: unknown };
}

interface PasswordlessSMSRequest {
  client_id?: string;
  phone_number: string;
}

interface PasswordlessEmailLoginRequest extends ClientCredentials {
  email: string;
  code?: string;
  scope?: string;
  audience?: string;
}

interface PasswordlessSMSLoginRequest extends ClientCredentials {
  phone_number: string;
  code: string;
  scope?: string;
  audience?: string;
}
```

### Backchannel Request Types

```typescript { .api }
interface BackchannelAuthorizationRequest extends ClientCredentials {
  scope?: string;
  login_hint?: string;
  id_token_hint?: string;
  login_hint_token?: string;
  binding_message?: string;
  user_code?: string;
  requested_expiry?: number;
}

interface BackchannelTokenRequest extends ClientCredentials {
  auth_req_id: string;
}
```

## Response Types

```typescript { .api }
interface SignUpResponse {
  _id: string;
  email: string;
  email_verified: boolean;
  username?: string;
}

interface PasswordlessResponse {
  _id?: string;
  phone_number?: string;
  phone_verified?: boolean;
  email?: string;
  email_verified?: boolean;
}

interface BackchannelAuthorizationResponse {
  auth_req_id: string;
  expires_in: number;
  interval?: number;
}

interface PushedAuthorizationResponse {
  request_uri: string;
  expires_in: number;
}
```

## Grant Options

```typescript { .api }
interface GrantOptions {
  idTokenValidateOptions?: Pick<IDTokenValidateOptions, 'organization'>;
  initOverrides?: InitOverride;
}

interface AuthorizationCodeGrantOptions {
  idTokenValidateOptions?: IDTokenValidateOptions;
  initOverrides?: InitOverride;
}

interface IDTokenValidateOptions {
  issuer?: string;
  audience?: string | string[];
  algorithm?: string;
  organization?: string;
  clockTolerance?: number;
  nonce?: string;
  maxAge?: number;
}
```

## Client Credentials

```typescript { .api }
interface ClientCredentials {
  client_id?: string;
  client_secret?: string;
  client_assertion?: string;
  client_assertion_type?: string;
}
```

## Constants

```typescript { .api }
const TOKEN_FOR_CONNECTION_GRANT_TYPE = 'urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token';
```