This page provides practical code examples for common authentication scenarios using the Authentication API client. It demonstrates how to implement various OAuth 2.0 flows, passwordless authentication, token management, and advanced authentication features supported by the Auth0 Python SDK.
For architectural details about the Authentication API structure, see Authentication API. For information about token acquisition flows and their technical implementation, see Token Acquisition (OAuth 2.0 Flows). For Management API usage examples, see Management API Examples. For asynchronous authentication patterns, see Async Usage Patterns.
The GetToken client is the primary interface for authentication operations in the SDK. It supports both synchronous and asynchronous modes.
Basic Initialization Pattern:
from auth0.authentication import GetToken
token_client = GetToken(
domain="your-tenant.auth0.com",
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET"
)
The client requires:
domain: Your Auth0 tenant domain (without protocol)client_id: Application client ID from Auth0 dashboardclient_secret: Application client secret (optional for public clients)Sources: README.md47-61
The client credentials flow is used for machine-to-machine authentication where the application authenticates itself to access an API.
Usage Pattern:
The client_credentials() method obtains an access token using the application's credentials. The token can be used to access APIs that trust the Auth0 tenant.
Key Parameters:
audience: The unique identifier of the target API (e.g., https://your-tenant.auth0.com/api/v2/)organization (optional): Organization ID for organization-specific tokens (added in v4.6.0)Response Format:
Returns a dictionary containing:
access_token: The JWT access tokentoken_type: Always "Bearer"expires_in: Token lifetime in secondsSources: README.md56-61 CHANGELOG.md140
The authorization code flow with Proof Key for Code Exchange (PKCE) is used for web and mobile applications where user interaction is required. PKCE adds security by generating a code verifier and challenge.
Implementation Steps:
authorization_url() method to construct the URL with PKCE parametersauthorization_code_exchange() to exchange the code for tokensKey Parameters:
redirect_uri: The callback URL registered in Auth0code_verifier: Random string for PKCE securitycode_challenge: SHA-256 hash of code_verifier, base64url encodedcode_challenge_method: Always "S256" for SHA-256state: Random value for CSRF protectionscope: Requested permissions (e.g., "openid profile email")Sources: CHANGELOG.md542-548
The resource owner password grant allows users to authenticate directly with username and password credentials. This flow should only be used when redirect-based flows cannot be implemented.
Authentication Method:
The login() method exchanges user credentials for tokens. The method requires:
username: User's email or usernamepassword: User's passwordrealm: The connection name (e.g., "Username-Password-Authentication")scope: Requested OAuth scopesaudience (optional): Target API identifierAdditional Options:
forwarded_for: IP address for audit logging (added in v4.3.0)Security Considerations:
This flow exposes user credentials to the application and should be avoided when possible. Use authorization code + PKCE for better security.
Sources: CHANGELOG.md177
Refresh tokens allow applications to obtain new access tokens without requiring user re-authentication.
Refresh Process:
The refresh_token() method exchanges a valid refresh token for a new access token and optionally a new refresh token.
Parameters:
refresh_token: The refresh token obtained during initial authenticationclient_id: Application client IDclient_secret (optional): Required for confidential clientsscope (optional): Can request reduced scope from original grantToken Rotation:
Some configurations enable refresh token rotation, where each refresh operation issues a new refresh token and invalidates the old one. Always update stored tokens after each refresh.
Sources: CHANGELOG.md530 README.md47-61
Passwordless authentication allows users to authenticate using email or SMS without traditional passwords.
Two-Step Process:
passwordless_start() to send a verification codepasswordless_login() with the received codeStart Method Parameters:
connection_type: Either "email" or "sms"email or phone_number: User identifiersend: "link" or "code" for delivery methodclient_secret: Application credentialsLogin Method Parameters:
username: Email or phone numberotp: The one-time code received by userrealm: "email" or "sms" matching the connection typescope: Requested permissionsSources: CHANGELOG.md303 CHANGELOG.md389
CIBA enables authentication flows where the user authenticates on a different device from where the authentication was initiated. This is useful for scenarios like smart TV login or IoT device authentication.
CIBA Flow Implementation:
back_channel_login() with user identifierauth_req_idLogin Method Parameters:
login_hint: User identifier (email, phone, or other)binding_message (optional): Short message shown to user for verificationclient_id: Application identifierscope: Requested permissionsauthorization_details (optional): RAR parameters for fine-grained authorizationPolling Behavior:
Enhanced Features (v4.12.0):
Sources: CHANGELOG.md54-58 CHANGELOG.md77 CHANGELOG.md83 CHANGELOG.md96
Token revocation invalidates refresh tokens or access tokens before their natural expiration.
Revocation Method:
The revoke_refresh_token() method invalidates a refresh token, preventing it from being used to obtain new access tokens.
Parameters:
refresh_token: The token to revokeclient_id: Application identifierclient_secret: Application secretUse Cases:
Sources: CHANGELOG.md461
Token verification ensures the authenticity and validity of tokens received by your application.
Verification Components:
The SDK provides specialized classes for token verification:
TokenVerifier: Main verification orchestratorAsymmetricSignatureVerifier: Handles RS256 signature verification using JWKSVerification Process:
Verifier Configuration:
algorithm: Token signing algorithm (typically "RS256")issuer: Expected token issuer (e.g., https://your-tenant.auth0.com/)audience: Expected audience claimleeway: Allowed time skew in seconds for expiration checksJWKS Caching:
The AsymmetricSignatureVerifier caches JWKS keys to reduce network requests. Cache behavior:
cache_ttl: Cache lifetime in seconds (added in v4.2.0)Async Support:
Async token verification (added in v3.24.0) enables non-blocking verification operations in async applications.
Return Value:
The verify() method returns the decoded token claims as a dictionary (feature added in v3.22.0).
Sources: CHANGELOG.md190 CHANGELOG.md235 CHANGELOG.md260
PAR enhances security by sending authorization parameters through a backchannel POST request instead of in the browser URL.
Benefits:
PAR Method Parameters:
response_type: OAuth response type (typically "code")client_id: Application identifierredirect_uri: Callback URLcode_challenge: PKCE code challengecode_challenge_method: "S256"scope: Requested permissionsResponse:
request_uri: Opaque identifier for the stored request (prefixed with "urn:ietf:params:oauth:request_uri:")expires_in: URI lifetime in seconds (typically 60-90 seconds)Implementation Note:
After obtaining the request_uri, construct the authorization URL using only the request_uri and client_id parameters. All other parameters are retrieved by the authorization server using the request URI.
Sources: CHANGELOG.md127 CHANGELOG.md89
JAR enables sending authorization request parameters as a signed JWT, providing request integrity and optional encryption.
JAR Parameters:
request: A JWT containing all authorization parametersRequest JWT Claims:
iss: Client ID (issuer of the request)aud: Authorization server URLiat: Issuance timeexp: Expiration timeSources: CHANGELOG.md95
RAR enables fine-grained authorization by allowing applications to request specific permissions with detailed context.
Authorization Details Structure:
RAR uses the authorization_details parameter containing an array of objects. Each object specifies:
type: The authorization type identifierExample Use Cases:
Integration with CIBA:
RAR is particularly useful with CIBA (added in v4.9.0), allowing the authentication device to display specific permission requests to the user.
Parameter Format:
authorization_details=[
{
"type": "account_information",
"accounts": ["12345", "67890"],
"actions": ["read"]
}
]
Sources: CHANGELOG.md83 CHANGELOG.md95
Private Key JWT (private_key_jwt) is a client authentication method using asymmetric cryptography instead of client secrets.
Authentication Mechanism:
Instead of sending client_secret, the client sends a client_assertion parameter containing:
client_assertion_type: Always "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"JWT Assertion Claims:
iss: Client ID (issuer)sub: Client ID (subject)aud: Token endpoint URLjti: Unique JWT identifierexp: Expiration timeiat: Issuance timeBenefits:
Setup Requirements:
The client's public key must be registered with Auth0 (via JWKS URL or direct registration) before using this authentication method.
Sources: CHANGELOG.md210
Organizations allow partitioning users and applications into isolated tenants within a single Auth0 environment.
Organization Parameters:
When authenticating, specify the organization using:
organization: Organization ID or nameIntegration Points:
org_id claim in tokensOrganization ID Validation:
Access tokens for organization requests include an org_id claim. Applications should verify:
org_id claim existsOrganization Name Validation:
Organization names must meet specific format requirements. The SDK includes validation (added in v4.4.0) to ensure names conform to Auth0's naming rules.
Password Change Support:
The change_password() method supports organization parameter (added in v4.6.0), allowing password reset flows within organization context.
Sources: CHANGELOG.md140-141 CHANGELOG.md167 CHANGELOG.md326 CHANGELOG.md327
| Flow | Use Case | User Interaction | Security Level | Token Types |
|---|---|---|---|---|
| Client Credentials | Machine-to-machine | None | Medium | Access token only |
| Authorization Code + PKCE | Web/mobile apps | Required | High | Access + ID + Refresh |
| Resource Owner Password | Trusted applications | Direct credentials | Low | Access + ID + Refresh |
| Passwordless | Frictionless login | Email/SMS code | Medium | Access + ID |
| CIBA | Cross-device auth | Separate device | High | Access + ID + Refresh |
The Authentication API implementation uses these primary components:
| Component | Purpose | Key Methods |
|---|---|---|
GetToken | Main authentication client | client_credentials(), authorization_code_exchange(), refresh_token() |
TokenVerifier | Token validation | verify() |
AsymmetricSignatureVerifier | RS256 signature verification | Signature validation with JWKS |
| Passwordless API | Passwordless flows | passwordless_start(), passwordless_login() |
| Database API | Username/password auth | login(), change_password() |
HTTP Dependencies:
requests library for synchronous operations requirements.txt11aiohttp library for asynchronous operations requirements.txt8pyjwt for JWT handling requirements.txt10cryptography for cryptographic operations requirements.txt9Sources: requirements.txt1-13 README.md47-61
Refresh this wiki