### Basic Authentication Flow Example Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/AuthenticationAPIClient.md A comprehensive example of setting up and performing a username-password login using AuthenticationAPIClient. Includes handling successful authentication and various error scenarios like invalid credentials, MFA, and network errors. ```kotlin import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationAPIClient import com.auth0.android.callback.Callback import com.auth0.android.authentication.AuthenticationException import com.auth0.android.result.Credentials class AuthActivity : AppCompatActivity() { private lateinit var authClient: AuthenticationAPIClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") authClient = AuthenticationAPIClient(auth0) } private fun performLogin(email: String, password: String) { authClient.login(email, password, "Username-Password-Authentication") .setScope("openid profile email offline_access") .start(object : Callback { override fun onSuccess(credentials: Credentials) { saveCredentials(credentials) goToMainScreen() } override fun onFailure(error: AuthenticationException) { when { error.isInvalidCredentials -> { showError("Invalid email or password") } error.isMultifactorRequired -> { handleMFARequired(error) } error.isNetworkError -> { showError("Network error") } else -> { showError(error.getDescription()) } } } }) } private fun handleMFARequired(error: AuthenticationException) { val mfaPayload = error.mfaRequiredErrorPayload if (mfaPayload != null) { val mfaClient = authClient.mfaClient(mfaPayload.mfaToken) // Continue with MFA flow } } } ``` -------------------------------- ### Sign Up with a database connection Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This example demonstrates how to sign up a user with a database connection using the Auth0 Android SDK. It includes examples for using callbacks, coroutines, and Java. ```APIDOC ## Sign Up with a database connection ### Description This method allows users to sign up for an account using a database connection. It requires the user's email, password, and the name of the database connection. ### Method Signature `authentication.signUp(email: String, password: String, connection: String)` ### Parameters - **email** (String) - Required - The email address of the user. - **password** (String) - Required - The password for the user's account. - **connection** (String) - Required - The name of the database connection to use. ### Additional Operations - `.validateClaims()` - Mandatory call to validate claims before starting the sign-up process. ### Starting the Operation - `.start(callback: Callback)` - Initiates the sign-up process and handles the result via a callback. - `.await()` - (Coroutines) Suspends the coroutine until the sign-up is complete and returns `Credentials` or throws `AuthenticationException`. ### Request Example (Kotlin with Callback) ```kotlin authentication .signUp("info@auth0.com", "a secret password", "my-database-connection") .validateClaims() //mandatory .start(object: Callback { override fun onFailure(exception: AuthenticationException) { /* Handle error */ } override fun onSuccess(credentials: Credentials) { /* Handle success */ } }) ``` ### Request Example (Kotlin with Coroutines) ```kotlin try { val credentials = authentication .signUp("info@auth0.com", "a secret password", "my-database-connection") .validateClaims() .await() // Process credentials } catch (e: AuthenticationException) { // Handle error } ``` ### Request Example (Java) ```java authentication .signUp("info@auth0.com", "a secret password", "my-database-connection") .validateClaims() //mandatory .start(new Callback() { @Override public void onSuccess(@Nullable Credentials payload) { // Signed Up & Logged in! } @Override public void onFailure(@NonNull AuthenticationException error) { // Error! } }); ``` ### Notes - The default scope used is `openid profile email`. The `openid` scope is always enforced. ``` -------------------------------- ### Custom Storage Implementation Example Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/configuration.md An example implementation of the Storage interface. This serves as a template for creating custom storage solutions. ```kotlin class CustomStorage : Storage { override fun store(key: String, value: String) { } override fun store(key: String, value: Long) { } override fun retrieveString(key: String): String? = null override fun retrieveLong(key: String): Long? = null override fun remove(key: String) { } override fun clear() { } } ``` -------------------------------- ### Constructor Example Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/README.md Illustrates the basic structure of a constructor with a single parameter. Use this as a template for understanding constructor definitions. ```kotlin public constructor(param: Type) ``` -------------------------------- ### Initialize Login Flow with Auth0 Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/WebAuthProvider.md Use this method to start the Auth0 Universal Login flow. Configure scopes, audience, and connection before starting. ```kotlin WebAuthProvider.login(auth0) .withScope("openid profile email offline_access") .withAudience("https://api.example.com") .withConnection("Username-Password-Authentication") .start(context, loginCallback) ``` -------------------------------- ### Get user information Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This example shows how to retrieve user profile information using an access token. It supports callbacks, coroutines, and Java. ```APIDOC ## Get user information ### Description This method retrieves the user's profile information using their access token. ### Method Signature `authentication.userInfo(accessToken: String)` ### Parameters - **accessToken** (String) - Required - The access token for the authenticated user. ### Starting the Operation - `.start(callback: Callback)` - Initiates the request and handles the result via a callback. - `.await()` - (Coroutines) Suspends the coroutine until the user info is retrieved and returns `UserProfile` or throws `AuthenticationException`. ### Request Example (Kotlin with Callback) ```kotlin authentication .userInfo("user access_token") .start(object: Callback { override fun onFailure(exception: AuthenticationException) { /* Handle error */ } override fun onSuccess(profile: UserProfile) { /* Process profile */ } }) ``` ### Request Example (Kotlin with Coroutines) ```kotlin try { val user = authentication .userInfo("user access_token") .await() // Process user profile } catch (e: AuthenticationException) { // Handle error } ``` ### Request Example (Java) ```java authentication .userInfo("user access_token") .start(new Callback() { @Override public void onSuccess(@Nullable UserProfile payload) { // Got the profile! } @Override public void onFailure(@NonNull AuthenticationException error) { // Error! } }); ``` ``` -------------------------------- ### Enroll Passkey with Java Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Enroll the created passkey credential with Auth0 using the provided challenge. This example uses Java and the callback API. ```java client.enroll(passkeyCredential, challenge) .start(new Callback() { @Override public void onSuccess(@NonNull PasskeyAuthenticationMethod result) { System.out.println("Passkey enrolled successfully: " + result.getId()); } @Override public void onFailure(@NonNull MyAccountException error) { System.out.println("Error enrolling passkey: " + error.getMessage()); } }); ``` -------------------------------- ### Enroll Passkey with Kotlin (Callback) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Enroll the created passkey credential with Auth0 using the provided challenge. This example uses the callback API. ```kotlin client.enroll(passkeyCredential,challenge) .start(object: Callback { override fun onSuccess(result: PasskeyAuthenticationMethod) { println("Passkey enrolled successfully: ${result.id}") } override fun onFailure(error: MyAccountException) { println("Error enrolling passkey: ${error.message}") } }) ``` -------------------------------- ### Configure Web Authentication with Options Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/INDEX.md Configures and starts a web-based authentication flow with various options like scopes, audience, and custom tabs. ```kotlin // Web authentication with full configuration WebAuthProvider.login(auth0) .withScheme("https") .withScope("openid profile email offline_access") .withAudience("https://api.example.com") .withConnection("google-oauth2") .withCustomTabsOptions(customOptions) .useDPoP(context) .start(activity, callback) ``` -------------------------------- ### Install Auth0.Android SDK with Gradle Source: https://github.com/auth0/auth0.android/blob/main/README.md Add the Auth0.Android SDK dependency to your `build.gradle` file to include it in your project. ```gradle dependencies { implementation 'com.auth0.android:auth0:3.19.0' } ``` -------------------------------- ### Initialize Logout Flow Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/WebAuthProvider.md Use this method to start the logout process. Configure the callback URI scheme before starting the flow. ```kotlin WebAuthProvider.logout(auth0) .withScheme("https") .start(context, logoutCallback) ``` -------------------------------- ### Get API Credentials with Java Callback Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java example shows how to retrieve API credentials using a callback mechanism. It requires specifying the audience, scope, and other parameters for the request. ```java credentialsManager.getApiCredentials("audience", "scope", 0, new HashMap<>(), new HashMap<>(), new Callback() { @Override public void onSuccess(APICredentials result) { System.out.println(result); } @Override public void onFailure(@NonNull CredentialsManagerException error) { System.out.println(error); } }); ``` -------------------------------- ### Auth0.getInstance(clientId: String, domain: String, configurationDomain: String?) Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Auth0.md Static factory method for on-premise installations or when the configuration domain differs from the authentication domain. ```APIDOC ## Auth0.getInstance(clientId: String, domain: String, configurationDomain: String?) ### Description Static factory method for on-premise installations or when configuration domain differs from authentication domain. ### Method `static factory method` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin // For on-premise Auth0 with separate configuration domain val auth0 = Auth0.getInstance( "YOUR_CLIENT_ID", "auth.example.com", "config.example.com" ) ``` ### Response #### Success Response `Auth0` instance #### Response Example ```kotlin val auth0 = Auth0.getInstance( "YOUR_CLIENT_ID", "auth.example.com", "config.example.com" ) ``` ``` -------------------------------- ### Complete User Login Example Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/README.md This snippet demonstrates a full user login flow using the AuthenticationAPIClient. It handles success and various failure scenarios, including invalid credentials and multi-factor authentication. ```kotlin val auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") val authClient = AuthenticationAPIClient(auth0) authClient.login("user@example.com", "password", "Username-Password-Authentication") .setScope("openid profile email offline_access") .setAudience("https://api.example.com") .start(object : Callback { override fun onSuccess(credentials: Credentials) { println("User: ${credentials.user.email}") saveCredentials(credentials) } override fun onFailure(error: AuthenticationException) { when { error.isInvalidCredentials -> println("Wrong email or password") error.isMultifactorRequired -> handleMFA(error) else -> println("Error: ${error.getDescription()}") } } }) ``` -------------------------------- ### Create Passkey Credential with Java Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Use the enrollment challenge with Google's CredentialManager APIs to create a new passkey credential. This example uses Java and asynchronous callbacks. ```java CreateCredentialRequest request = new CreatePublicKeyCredentialRequest(new Gson().toJson(enrollmentChallenge.authParamsPublicKey())); credentialManager.createCredentialAsync(getContext(), request, cancellationSignal, , new CredentialManagerCallback() { @Override public void onResult(CreateCredentialResponse createCredentialResponse) { PublicKeyCredentials credentials = new Gson().fromJson( ((CreatePublicKeyCredentialResponse) createCredentialResponse).getRegistrationResponseJson(), PublicKeyCredentials.class); } @Override public void onError(@NonNull CreateCredentialException e) {} }); ``` -------------------------------- ### Start Universal Login Authentication (Kotlin Callback) Source: https://github.com/auth0/auth0.android/blob/main/README.md Initiate the Universal Login flow using the WebAuthProvider and handle the authentication result via a callback. The callback receives either Credentials on success or an AuthenticationException on failure. ```kotlin val callback = object : Callback { override fun onFailure(exception: AuthenticationException) { // Failure! Check the exception for details } override fun onSuccess(credentials: Credentials) { // Success! Access token and ID token are presents } } WebAuthProvider.login(account) .start(this, callback) ``` -------------------------------- ### Create Passkey Credential with Kotlin Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Use the enrollment challenge with Google's CredentialManager APIs to create a new passkey credential. This example uses coroutines. ```kotlin // Using coroutines val request = CreatePublicKeyCredentialRequest( Gson().toJson(enrollmentChallenge.authParamsPublicKey) ) val result = credentialManager.createCredential(requireContext(), request) val passkeyCredentials = Gson().fromJson( (result as CreatePublicKeyCredentialResponse).registrationResponseJson, PublicKeyCredentials::class.java ) ``` -------------------------------- ### Initiate MFA Enrollment Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/MfaApiClient.md Starts the MFA enrollment process for a specified authenticator type. Requires a callback to handle the enrollment challenge or potential errors. ```kotlin mfaClient.enrollmentRequest("otp") .start(object : Callback { override fun onSuccess(challenge: EnrollmentChallenge) { println("Enrollment challenge created") // Present QR code or other enrollment UI } override fun onFailure(error: MfaEnrollmentException) {} }) ``` -------------------------------- ### Start Passkey Registration Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/AuthenticationAPIClient.md Initiates the passkey registration flow for a given user ID. Use the returned challenge data with the WebAuthn API to perform the actual registration. ```kotlin authClient.startPasskeyRegistration("auth0|userid") .start(object : Callback { override fun onSuccess(challenge: PasskeyRegistrationChallenge) { // Use challenge data with WebAuthn API performWebAuthnRegistration(challenge) } override fun onFailure(error: AuthenticationException) {} }) ``` -------------------------------- ### start(callback: Callback) Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Request.md Executes the request asynchronously using a callback. This method is safe to call from the main thread and will invoke the provided callback upon success or failure. ```APIDOC ## start(callback: Callback) ### Description Executes the request asynchronously using a callback. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```kotlin public fun start(callback: Callback) ``` ### Parameters - **callback** (Callback) - Required - Called on success or failure ### Behavior - Executes on background thread - Calls `callback.onSuccess()` with result on success - Calls `callback.onFailure()` with exception on failure - Safe to call from main thread ### Request Example ```kotlin authClient.login(email, password, connection) .addParameter("custom_param", "value") .start(object : Callback { override fun onSuccess(credentials: Credentials) { println("Login successful") } override fun onFailure(error: AuthenticationException) { println("Error: ${error.getCode()}") } }) ``` ``` -------------------------------- ### Enroll Passkey with Kotlin (Coroutines) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Enroll the created passkey credential with Auth0 using the provided challenge. This example uses coroutines and the await() function for asynchronous operations. ```kotlin try { val result = client.enroll(passkeyCredential, challenge) .await() println("Passkey enrolled successfully: ${result.id}") } catch(error: MyAccountException) { println("Error enrolling passkey: ${error.message}") } ``` -------------------------------- ### Coroutine Login Example Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Callback.md Demonstrates how to perform a login operation using Kotlin coroutines and the 'await' suspend function. Handles successful login and authentication errors. ```kotlin lifecycleScope.launch { try { val credentials = authClient.login(email, password, connection) .setScope("openid profile email offline_access") .await() saveCredentials(credentials) } catch (error: AuthenticationException) { showError(error.getDescription()) } } ``` -------------------------------- ### Specify Login Prompt and Custom Parameters Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Use the `.withParameters` method to prompt the user to log in or to send custom parameters in the authentication request. Example includes 'prompt' and a custom parameter. ```kotlin WebAuthProvider.login(account) .withParameters(mapOf("prompt" to "login", "custom" to "value")) .start(this, callback) ``` -------------------------------- ### Start Universal Login Authentication (Java Callback) Source: https://github.com/auth0/auth0.android/blob/main/README.md Initiate the Universal Login flow in Java using the WebAuthProvider and handle the authentication result via a callback interface. This is the standard Java approach for asynchronous operations. ```java Callback callback = new Callback() { @Override public void onFailure(@NonNull AuthenticationException exception) { //failed with an exception } @Override public void onSuccess(@Nullable Credentials credentials) { //succeeded! } }; WebAuthProvider.login(account) .start(this, callback); ``` -------------------------------- ### Enroll OTP (Authenticator App) in Java Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Initiates the OTP enrollment process in Java. This is the equivalent of the Kotlin example for users preferring Java. The secret and barcode URI are provided upon successful challenge. ```java mfaClient .enroll(MfaEnrollmentType.Otp.INSTANCE) .start(new Callback() { @Override public void onFailure(@NonNull MfaEnrollmentException exception) { } @Override public void onSuccess(EnrollmentChallenge enrollment) { // Display QR code or secret for user to scan/enter in authenticator app if (enrollment instanceof TotpEnrollmentChallenge) { TotpEnrollmentChallenge totpEnrollment = (TotpEnrollmentChallenge) enrollment; String secret = totpEnrollment.getManualInputCode(); String barcodeUri = totpEnrollment.getBarcodeUri(); } } }); ``` -------------------------------- ### Comprehensive Login Error Handling Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/errors.md Shows a complete example of handling various login-related errors, including invalid credentials, account lockouts, password leaks, MFA requirements, and network issues. ```kotlin authClient.login("user@example.com", "password", "Username-Password-Authentication") .start(object : Callback { override fun onFailure(error: AuthenticationException) { when { error.isInvalidCredentials -> { showError("Invalid email or password") } error.isTooManyAttempts -> { showError("Account locked. Try again later.") } error.isPasswordLeaked -> { showError("Password compromised. Please change it.") } error.isMultifactorRequired -> { val mfaToken = error.mfaRequiredErrorPayload?.mfaToken handleMFA(mfaToken) } error.isNetworkError -> { showError("Network error. Check your connection.") } else -> { showError("Error: ${error.getDescription()") } } } override fun onSuccess(credentials: Credentials) {} }) ``` -------------------------------- ### Perform Custom Token Exchange with Java Callbacks Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java example demonstrates custom token exchange using the SDK's callback mechanism for handling asynchronous results. ```java authentication .customTokenExchange("subject_token_type", "subject_token", "organization_id") .start(new Callback() { @Override public void onSuccess(@Nullable Credentials payload) { // Handle success } @Override public void onFailure(@NonNull AuthenticationException error) { // Handle error } }); ``` -------------------------------- ### SecureCredentialsManager with Custom AuthenticationAPIClient (Java) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java example shows how to set up SecureCredentialsManager using a custom AuthenticationAPIClient with DPoP. It requires an Auth0 instance, FragmentActivity, and configured local authentication. ```java Auth0 auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN"); AuthenticationAPIClient apiClient = new AuthenticationAPIClient(auth0).useDPoP(this); LocalAuthenticationOptions localAuthenticationOptions = new LocalAuthenticationOptions.Builder() .setTitle("Authenticate") .setDescription("Accessing Credentials") .setAuthenticationLevel(AuthenticationLevel.STRONG) .setNegativeButtonText("Cancel") .setDeviceCredentialFallback(true) .setPolicy(new BiometricPolicy.Session(300)) .build(); Storage storage = new SharedPreferencesStorage(this); SecureCredentialsManager secureCredentialsManager = new SecureCredentialsManager( apiClient, this, auth0, storage, fragmentActivity, localAuthenticationOptions); ``` -------------------------------- ### Build Sample App Source: https://github.com/auth0/auth0.android/blob/main/AGENTS.md Compile and package the sample application for debugging purposes using Gradle. ```bash # Build sample app ./gradlew sample:assembleDebug ``` -------------------------------- ### Get Auth0 Instance with Custom Configuration Domain Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Auth0.md Instantiate the Auth0 class when your configuration domain differs from your authentication domain, typically for on-premise installations. The configuration domain is optional. ```kotlin // For on-premise Auth0 with separate configuration domain val auth0 = Auth0.getInstance( "YOUR_CLIENT_ID", "auth.example.com", "config.example.com" ) ``` -------------------------------- ### Signup User with Passkey (Java) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java snippet demonstrates how to sign up a new user with a passkey. It utilizes callbacks for asynchronous operations and requires specific Auth0 dashboard configurations. ```java UserData userData = new UserData( "user@example.com", // email "+11234567890", // phoneNumber null, // userName "John Doe", // name "John", // givenName "Doe", // familyName "johnny", // nickName "https://example.com/photo.png", // picture Map.of("signup_source", "android_app") // userMetadata ); authenticationAPIClient.signupWithPasskey(userData, "{realm}","{organization-id}") .start(new Callback() { @Override public void onSuccess(PasskeyRegistrationChallenge result) { CreateCredentialRequest request = new CreatePublicKeyCredentialRequest(new Gson().toJson(result.getAuthParamsPublicKey())); credentialManager.createCredentialAsync(getContext(), request, cancellationSignal, , new CredentialManagerCallback() { @Override public void onResult(CreateCredentialResponse createCredentialResponse) { PublicKeyCredentials credentials = new Gson().fromJson( ((CreatePublicKeyCredentialResponse) createCredentialResponse).getRegistrationResponseJson(), PublicKeyCredentials.class); authenticationAPIClient.signinWithPasskey(result.getAuthSession(), credentials, "{realm}","{organization-id}") .start(new Callback() { @Override public void onSuccess(Credentials result) {} @Override public void onFailure(@NonNull AuthenticationException error) {} }); } @Override public void onError(@NonNull CreateCredentialException e) {} }); } @Override public void onFailure(@NonNull AuthenticationException error) {} }); ``` -------------------------------- ### Get Available MFA Factors with Kotlin Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves the list of multi-factor authentication (MFA) factors enabled for the tenant and available for the user. Requires the 'read:me:factors' scope. This example uses the callback API. ```kotlin myAccountClient.getFactors() .start(object : Callback, MyAccountException> { override fun onSuccess(result: Factors) { // List of available factors in result.factors } override fun onFailure(error: MyAccountException) { } }) ``` -------------------------------- ### Get Available MFA Factors with Java Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves the list of multi-factor authentication (MFA) factors enabled for the tenant and available for the user. Requires the 'read:me:factors' scope. This example uses Java and the callback API. ```java myAccountClient.getFactors() .start(new Callback, MyAccountException>() { @Override public void onSuccess(Factors result) { // List of available factors in result.getFactors() } @Override public void onFailure(@NonNull MyAccountException error) { } }); ``` -------------------------------- ### Auth0 Client Initialization and Configuration Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Auth0.md Demonstrates how to initialize the Auth0 client with your application's credentials and customize networking settings. ```APIDOC ## Properties ### clientId: String Your Auth0 application client identifier (read-only). ```kotlin public val clientId: String ``` ### domain: String Your Auth0 account domain hostname extracted from the domain URL (read-only). ```kotlin public val domain: String ``` ### configurationDomain: String? Custom domain for fetching Auth0 configuration. Used for on-premise installations (read-only). ```kotlin public val configurationDomain: String? ``` ### auth0UserAgent: Auth0UserAgent User agent information sent in every HTTP request. Can be customized for analytics purposes. ```kotlin public var auth0UserAgent: Auth0UserAgent = Auth0UserAgent() ``` ### networkingClient: NetworkingClient The HTTP client used to make requests. Defaults to `DefaultClient()`. Can be replaced with a custom implementation. ```kotlin public var networkingClient: NetworkingClient = DefaultClient() ``` **Example:** ```kotlin val auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") val customClient = CustomNetworkingClient() auth0.networkingClient = customClient ``` ### executor: Executor Single-threaded executor for background operations. All API clients created from this instance share this executor. ```kotlin public val executor: Executor ``` ``` -------------------------------- ### Authentication Client with Claim Validation (Java) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java example shows how to perform ID token validation for the Authentication Client. It uses the standard `Callback` interface for handling success and failure. ```java Auth0 auth0 = Auth0.getInstance("client id", "domain"); AuthenticationAPIClient client = new AuthenticationAPIClient(account); client .login("{username or email}", "{password}", "{database connection name}") .validateClaims() .withIdTokenVerificationIssuer("https://{YOUR_AUTH0_DOMAIN}/") .start(new Callback() { @Override public void onSuccess(@Nullable Credentials payload) { //Logged in! } @Override public void onFailure(@NonNull AuthenticationException error) { //Error! } }); ``` -------------------------------- ### Initialize Auth0 SDK with Client ID and Domain (Java) Source: https://github.com/auth0/auth0.android/blob/main/README.md Create an instance of the Auth0 SDK by providing your application's Client ID and Domain in Java. ```java Auth0 account = Auth0.getInstance("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}"); ``` -------------------------------- ### Update User Metadata with Java Callbacks Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md This Java example shows how to update user metadata using the SDK's callback mechanism. It requires standard Java collection and exception handling. ```java Map metadata = new HashMap<>(); metadata.put("name", Arrays.asList("My", "Name", "Is")); metadata.put("phoneNumber", "1234567890"); users .updateMetadata("user id", metadata) .start(new Callback() { @Override public void onSuccess(@Nullable UserProfile payload) { //User Metadata updated } @Override public void onFailure(@NonNull ManagementException error) { //Error! } }); ``` -------------------------------- ### Initialize and Use CredentialsManager Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/CredentialsManager.md This snippet shows how to set up the Auth0 client and CredentialsManager, check for existing valid credentials, and either fetch them or navigate to the login screen. ```kotlin import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationAPIClient import com.auth0.android.authentication.storage.CredentialsManager import com.auth0.android.authentication.storage.SharedPreferencesStorage import com.auth0.android.callback.Callback import com.auth0.android.authentication.AuthenticationException class LoginActivity : AppCompatActivity() { private lateinit var auth0: Auth0 private lateinit var manager: CredentialsManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Setup Auth0 auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") // Setup CredentialsManager val authClient = AuthenticationAPIClient(auth0) val storage = SharedPreferencesStorage(this) manager = CredentialsManager(authClient, storage) // Check if user is already logged in if (manager.hasValidCredentials()) { // Fetch credentials and use them manager.getCredentials(object : Callback { override fun onSuccess(credentials: Credentials) { goToMainScreen(credentials) } override fun onFailure(error: CredentialsManagerException) { goToLoginScreen() } }) } else { goToLoginScreen() } } private fun logout() { manager.clearCredentials() goToLoginScreen() } } ``` -------------------------------- ### Get User Profile Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves the profile information for a specific user based on their user ID. ```APIDOC ## Get User Profile ### Description Retrieves the profile information for a specific user. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user whose profile to retrieve. ### Request Example ```kotlin users.getProfile("user id") ``` ### Response #### Success Response - **profile** (UserProfile) - An object containing the user's profile information. #### Response Example ```json { "user_id": "auth0|abcdef1234567890", "email": "test@example.com", "name": "Test User" } ``` ``` -------------------------------- ### Get a Single Authentication Method by ID Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves a single authentication method using its unique identifier. ```APIDOC ## Get a Single Authentication Method by ID ### Description Retrieves a single authentication method by its unique ID. ### Method ```kotlin myAccountClient.getAuthenticationMethodById(id: String) ``` ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the authentication method. ### Request Example ```kotlin myAccountClient.getAuthenticationMethodById("phone|dev_...") .start(object : Callback { override fun onSuccess(result: AuthenticationMethod) { // The requested authentication method } override fun onFailure(error: MyAccountException) { } }) ``` ### Response #### Success Response (200) - **result** (AuthenticationMethod) - The details of the requested authentication method. #### Response Example ```json { "type": "PASSKEY", "id": "passkey|abc123xyz" } ``` ``` -------------------------------- ### Initialize Auth0 SDK Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Auth0.md Shows how to initialize the Auth0 SDK with your client ID and domain, and create an AuthenticationAPIClient for authentication operations. Ensure you replace 'YOUR_CLIENT_ID' and 'YOUR_DOMAIN' with your actual Auth0 credentials. ```kotlin import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationAPIClient class MainActivity : AppCompatActivity() { private lateinit var auth0: Auth0 private lateinit var authClient: AuthenticationAPIClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize Auth0 auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN") // Create authentication client authClient = AuthenticationAPIClient(auth0) // Log the configured domain println("Auth0 Domain: ${auth0.domain}") println("Authorize URL: ${auth0.authorizeUrl}") } } ``` -------------------------------- ### MFA Enrollment - Get Authenticators Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/INDEX.md Retrieves available MFA authenticators after a user has logged in, preparing for enrollment. ```text 1. Get available authenticators after login → mfaClient.getAuthenticators(factors) ``` -------------------------------- ### Full Build with Tests and Coverage Source: https://github.com/auth0/auth0.android/blob/main/AGENTS.md Execute a full project build, including running unit tests and generating code coverage reports using Gradle. ```bash # Full build with tests and coverage ./gradlew clean test jacocoTestReport ``` -------------------------------- ### Sign Up with Database Connection (Java Callback) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Sign up a user with a database connection using Java callbacks. The `validateClaims()` method is mandatory. ```java authentication .signUp("info@auth0.com", "a secret password", "my-database-connection") .validateClaims() //mandatory .start(new Callback() { @Override public void onSuccess(@Nullable Credentials payload) { //Signed Up & Logged in! } @Override public void onFailure(@NonNull AuthenticationException error) { //Error! } }); ``` -------------------------------- ### Iterate Through User Identities Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/types.md Example of how to retrieve and iterate through a user's identities to display provider and user ID information. ```kotlin val identities = profile.getIdentities() for (identity in identities) { println("Provider: ${identity.provider}") println("User ID: ${identity.userId}") } ``` -------------------------------- ### Initialize Auth0 SDK using Android Context Source: https://github.com/auth0/auth0.android/blob/main/README.md Configure Auth0 SDK by saving your Client ID and Domain in `strings.xml` and initializing the SDK with an Android Context. ```xml YOUR_CLIENT_ID YOUR_DOMAIN ``` ```kotlin val account = Auth0.getInstance(context) ``` -------------------------------- ### Initialize My Account API Client Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Instantiate the MyAccountAPIClient with your Auth0 instance and an access token. ```kotlin val client = MyAccountAPIClient(auth0, accessToken) ``` -------------------------------- ### enrollmentRequest Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/MfaApiClient.md Initiates MFA enrollment for a new authenticator type. This method returns a Request object that can be used to start the enrollment process. ```APIDOC ## enrollmentRequest(authenticatorType: String) ### Description Initiates MFA enrollment for a new authenticator type. ### Method Signature `public fun enrollmentRequest(authenticatorType: String): Request` ### Parameters #### Path Parameters - **authenticatorType** (String) - Required - Authenticator type to enroll ("otp", "webauthn", etc.) ### Returns Request yielding EnrollmentChallenge ### Request Example ```kotlin mfaClient.enrollmentRequest("otp") .start(object : Callback { override fun onSuccess(challenge: EnrollmentChallenge) { println("Enrollment challenge created") // Present QR code or other enrollment UI } override fun onFailure(error: MfaEnrollmentException) {} }) ``` ``` -------------------------------- ### Reusing a Request Object Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/Request.md A Request object can be reused to execute multiple network operations. Each `start()` call initiates a new operation. ```kotlin val request = authClient.login(email, password, connection) .setScope("openid profile email") // Execute multiple times (not recommended, but possible) request.start(callback1) request.start(callback2) // Creates new network operation ``` -------------------------------- ### Sign Up with Database Connection (Kotlin Callback) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Use this method to sign up a user with a database connection using callbacks. Ensure `validateClaims()` is called. ```kotlin authentication .signUp("info@auth0.com", "a secret password", "my-database-connection") .validateClaims() //mandatory .start(object: Callback { override fun onFailure(exception: AuthenticationException) { } override fun onSuccess(credentials: Credentials) { } }) ``` -------------------------------- ### Setup SecureCredentialsManager Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/configuration.md Instantiate SecureCredentialsManager, which requires an Android Context in addition to the AuthenticationAPIClient, Auth0 configuration, and Storage. This provides enhanced security. ```kotlin val auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") val authClient = AuthenticationAPIClient(auth0) val storage = SharedPreferencesStorage(context) val manager = SecureCredentialsManager(authClient, context, auth0, storage) ``` -------------------------------- ### Create MFA Challenge Request Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/MfaApiClient.md Initiates an out-of-band MFA challenge (push, SMS, or email). Use this to start the MFA process for a user. ```kotlin public fun challengeRequest( authenticatorId: String, challengeType: String ): Request ``` ```kotlin mfaClient.challengeRequest(authenticatorId, "oob") .start(object : Callback { override fun onSuccess(challenge: Challenge) { println("Challenge created: ${challenge.challengeType}") // Wait for user to approve push notification or enter code } override fun onFailure(error: MfaChallengeException) {} }) ``` -------------------------------- ### Initialize My Account API Client with DPoP Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Enable DPoP (Demonstrating Proof of Possession) on the MyAccountAPIClient for secure API calls. This automatically uses the DPoP authorization scheme and includes the necessary header. ```kotlin val client = MyAccountAPIClient(auth0, accessToken).useDPoP(context) ``` ```java MyAccountAPIClient client = new MyAccountAPIClient(auth0, accessToken).useDPoP(context); ``` -------------------------------- ### Get All Enrolled Authentication Methods Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves a detailed list of all authentication methods enrolled by the current user. Results can be optionally filtered by type. ```APIDOC ## Get All Enrolled Authentication Methods ### Description Retrieves a detailed list of all the authentication methods that the current user has already enrolled in. You can optionally filter the results by type using `AuthenticationMethodType`. ### Method ```kotlin myAccountClient.getAuthenticationMethods() ``` ### Parameters #### Query Parameters - **type** (AuthenticationMethodType) - Optional - Filters the results by the specified authentication method type. ### Request Example ```kotlin // Get all authentication methods myAccountClient.getAuthenticationMethods() .start(object : Callback, MyAccountException> { override fun onSuccess(result: List) { // List of enrolled methods } override fun onFailure(error: MyAccountException) { } }) // Get authentication methods filtered by type myAccountClient.getAuthenticationMethods(AuthenticationMethodType.PASSKEY) .start(object : Callback, MyAccountException> { override fun onSuccess(result: List) { // List of enrolled passkey methods only } override fun onFailure(error: MyAccountException) { } }) ``` ### Response #### Success Response (200) - **result** (List) - A list of enrolled authentication methods. #### Response Example ```json [ { "type": "PASSKEY", "id": "passkey|abc123xyz" }, { "type": "SMS", "id": "sms|def456uvw" } ] ``` ``` -------------------------------- ### Get Single Authentication Method by ID Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves a specific authentication method using its unique identifier. Ensure the user has the method enrolled. ```kotlin myAccountClient.getAuthenticationMethodById("phone|dev_...") .start(object : Callback { override fun onSuccess(result: AuthenticationMethod) { // The requested authentication method } override fun onFailure(error: MyAccountException) { } }) ``` ```java myAccountClient.getAuthenticationMethodById("phone|dev_...") .start(new Callback() { @Override public void onSuccess(AuthenticationMethod result) { // The requested authentication method } @Override public void onFailure(@NonNull MyAccountException error) { } }); ``` -------------------------------- ### Create AuthenticationAPIClient Instance Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/AuthenticationAPIClient.md Instantiate the AuthenticationAPIClient with your Auth0 account configuration. Ensure you have initialized Auth0 with your client ID and domain. ```kotlin val auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN") val client = AuthenticationAPIClient(auth0) ``` -------------------------------- ### MfaChallengeException Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/errors.md Raised during MFA challenge operations. Provides methods to get the error code and description, and properties to check for invalid tokens or requests. ```APIDOC ## MfaChallengeException ### Description Raised during MFA challenge operations. ### Triggers: - Invalid MFA token - Invalid authenticator ID - Challenge type not available ### Methods - `getCode()`: Returns the error code. - `getDescription()`: Returns a detailed error description. ### Properties - `isInvalidToken` (Boolean): True if the MFA token is invalid. - `isInvalidRequest` (Boolean): True if the challenge request was invalid. ``` -------------------------------- ### User Signup with Username/Password Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/AuthenticationAPIClient.md Create a new user account in a database connection. Handles successful creation and specific authentication errors like weak passwords or already used passwords. ```kotlin authClient.signUp("newuser@example.com", "SecurePass123!", "Username-Password-Authentication") .start(object : Callback { override fun onSuccess(user: DatabaseUser) { println("Signup successful for: ${user.email}") // User created, may need email verification } override fun onFailure(error: AuthenticationException) { when { error.isPasswordNotStrongEnough -> println("Password too weak") else -> println("Error: ${error.getDescription()}") } } }) ``` -------------------------------- ### signUp Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/api-reference/AuthenticationAPIClient.md Creates a new user in a database connection. ```APIDOC ## signUp(email: String, password: String, connection: String) ### Description Creates a new user in a database connection. ### Method POST ### Endpoint /dbconnections/sign-up ### Parameters #### Path Parameters - **email** (String) - Required - User email address - **password** (String) - Required - User password (must meet connection strength requirements) - **connection** (String) - Required - Database connection name ### Request Example ```kotlin authClient.signUp("newuser@example.com", "SecurePass123!", "Username-Password-Authentication") .start(object : Callback { override fun onSuccess(user: DatabaseUser) { println("Signup successful for: ${user.email}") // User created, may need email verification } override fun onFailure(error: AuthenticationException) { when { error.isPasswordNotStrongEnough -> println("Password too weak") else -> println("Error: ${error.getDescription()}") } } }) ``` ### Response #### Success Response (200) - **DatabaseUser** (DatabaseUser) - On success #### Response Example (Response body structure depends on the DatabaseUser object) ### Error Handling - **AuthenticationException (isPasswordNotStrongEnough)** - Password doesn't meet strength requirements - **AuthenticationException (isPasswordAlreadyUsed)** - Password was previously used (if history enabled) ``` -------------------------------- ### Setup SecureCredentialsManager with Biometrics Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/configuration.md Configure SecureCredentialsManager to use biometric authentication. This involves defining LocalAuthenticationOptions for the prompt and then using the biometrics factory method. ```kotlin val options = LocalAuthenticationOptions( title = "Authenticate to access credentials", description = "Biometric authentication required", authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG ) val manager = SecureCredentialsManager.biometrics( context, auth0, storage, options ) ``` -------------------------------- ### Initialize Auth0 Instance with Client ID and Domain Source: https://github.com/auth0/auth0.android/blob/main/_autodocs/configuration.md Initialize the Auth0 instance directly with your client ID and domain strings. This method is useful when you need to provide credentials programmatically. ```kotlin val auth0 = Auth0.getInstance("CLIENT_ID", "DOMAIN") ``` -------------------------------- ### Get All Enrolled Authentication Methods Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieves a list of all authentication methods enrolled by the current user. Use the overload to filter by a specific method type. ```kotlin myAccountClient.getAuthenticationMethods() .start(object : Callback, MyAccountException> { override fun onSuccess(result: List) { // List of enrolled methods } override fun onFailure(error: MyAccountException) { } }) myAccountClient.getAuthenticationMethods(AuthenticationMethodType.PASSKEY) .start(object : Callback, MyAccountException> { override fun onSuccess(result: List) { // List of enrolled passkey methods only } override fun onFailure(error: MyAccountException) { } }) ``` ```java myAccountClient.getAuthenticationMethods() .start(new Callback, MyAccountException>() { @Override public void onSuccess(List result) { // List of enrolled methods } @Override public void onFailure(@NonNull MyAccountException error) { } }); myAccountClient.getAuthenticationMethods(AuthenticationMethodType.PASSKEY) .start(new Callback, MyAccountException>() { @Override public void onSuccess(List result) { // List of enrolled passkey methods only } @Override public void onFailure(@NonNull MyAccountException error) { } }); ``` -------------------------------- ### Initialize MyAccountAPIClient with DPoP Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Initializes the MyAccountAPIClient and enables DPoP for enhanced security. ```APIDOC ## Initialize MyAccountAPIClient with DPoP ### Description Initializes the MyAccountAPIClient and enables DPoP (Demonstrating Proof of Possession) for enhanced security. When DPoP is enabled, the client automatically uses the `DPoP` authorization scheme and includes a DPoP proof header on every request. ### Code Example (Kotlin) ```kotlin val client = MyAccountAPIClient(auth0, accessToken).useDPoP(context) ``` ### Code Example (Java) ```java MyAccountAPIClient client = new MyAccountAPIClient(auth0, accessToken).useDPoP(context); ``` ``` -------------------------------- ### Get User Info (Java Callback) Source: https://github.com/auth0/auth0.android/blob/main/EXAMPLES.md Retrieve user profile information using a Java callback. This method requires a user access token. ```java authentication .userInfo("user access_token") .start(new Callback() { @Override public void onSuccess(@Nullable UserProfile payload) { //Got the profile! } @Override public void onFailure(@NonNull AuthenticationException error) { //Error! } }); ```