auth0-android

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Android Integration

Auth0 Android 集成

Add authentication to Android applications using
com.auth0.android:auth0
.
Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:
gh api repos/auth0/Auth0.Android/releases/latest --jq '.tag_name'
Use the returned version in all
implementation
dependency lines instead of any hardcoded version below. If the command fails, fall back to checking https://github.com/auth0/Auth0.Android/releases.
使用
com.auth0.android:auth0
为Android应用添加认证功能。
Agent 指令: 在提供SDK设置说明前,运行以下命令获取最新版本:
gh api repos/auth0/Auth0.Android/releases/latest --jq '.tag_name'
将返回的版本替换以下所有
implementation
依赖行中的硬编码版本。如果命令执行失败,可查看https://github.com/auth0/Auth0.Android/releases获取最新版本。

Prerequisites

前提条件

  • Android API 21 or higher
  • Kotlin or Java project
  • Auth0 account with a Native application configured
  • If you don't have Auth0 set up, see auth0-quickstart
  • Android API 21 或更高版本
  • Kotlin 或 Java 项目
  • 已配置原生应用的Auth0账号
  • 若未设置Auth0,请查看auth0-quickstart

When NOT to Use

不适用于以下场景

Quick Start Workflow

快速开始流程

  1. Install SDK: Add the Auth0 Android SDK dependency to your
    build.gradle
    :
    gradle
    implementation 'com.auth0.android:auth0:{LATEST_VERSION}'
  2. Configure Auth0:
    Agent instruction: Check whether the user prompt already includes both Auth0 Client ID and Domain.
    • If both are provided, proceed directly to Manual Setup in Setup Guide using those values.
    • If either is missing, you MUST ask the user BEFORE writing any code or files:
      • Question: "How would you like to configure Auth0 for this project?"
      • Options: "Automatic setup (Recommended) — Auth0 CLI creates the app and writes credentials to strings.xml" / "Manual setup — I'll provide my Client ID and Domain"
    Then follow Setup Guide for the chosen path. Do NOT proceed to step 3 until Auth0 credentials are confirmed.
    Note: For native Android apps, Domain and Client ID are public configuration (not secrets). No client secret is used. Write values directly to
    strings.xml
    without displaying them in conversation output.
  3. Initialize: Create an Auth0 account instance:
    kotlin
    import com.auth0.android.Auth0
    
    val account = Auth0.getInstance(context)
  4. Add Auth UI: Implement login and logout with Web Auth:
    Agent instruction: Before adding new UI elements, search the project for existing click handlers for login, logout, sign-in, or sign-out buttons (e.g.,
    loginButton
    ,
    signInButton
    ,
    logoutButton
    ,
    signOutButton
    , or
    setOnClickListener
    with auth-related naming). If existing handlers are found, hook the Auth0 code into them without modifying the existing UI. Only create new buttons if no existing handlers are found.
    Login:
    kotlin
    import com.auth0.android.Auth0
    import com.auth0.android.authentication.AuthenticationAPIClient
    import com.auth0.android.authentication.storage.SecureCredentialsManager
    import com.auth0.android.authentication.storage.SharedPreferencesStorage
    import com.auth0.android.callback.Callback
    import com.auth0.android.authentication.AuthenticationException
    import com.auth0.android.provider.WebAuthProvider
    import com.auth0.android.result.Credentials
    
    val account = Auth0.getInstance(context)
    val authentication = AuthenticationAPIClient(account)
    val storage = SharedPreferencesStorage(context)
    val credentialsManager = SecureCredentialsManager(context, authentication, storage)
    
    WebAuthProvider.login(account)
        .withScheme(getString(R.string.com_auth0_scheme))
        .withScope("openid profile email offline_access")
        .start(this, object : Callback<Credentials, AuthenticationException> {
            override fun onSuccess(result: Credentials) {
                // User authenticated
                val idToken = result.idToken
                val accessToken = result.accessToken
                // Store credentials securely
                credentialsManager.saveCredentials(result)
            }
            override fun onFailure(error: AuthenticationException) {
                // Handle authentication failure
                Log.e("Auth0", "Authentication failed", error)
            }
        })
    Logout:
    kotlin
    WebAuthProvider.logout(account)
        .withScheme(getString(R.string.com_auth0_scheme))
        .start(this, object : Callback<Void?, AuthenticationException> {
            override fun onSuccess(result: Void) {
                // User logged out
            }
            override fun onFailure(error: AuthenticationException) {
                Log.e("Auth0", "Logout failed", error)
            }
        })
  5. Build & Verify:
    Agent instruction: After completing the integration, build the project to verify it compiles successfully:
    bash
    ./gradlew assembleDebug
    If the build fails, analyze the error output and fix the issues. Common integration build failures include:
    • Unresolved reference: Missing import statements — add the required
      import com.auth0.android.*
      imports
    • Cannot resolve symbol
      R.string.com_auth0_scheme
      :
      strings.xml
      not updated — verify
      com_auth0_scheme
      ,
      com_auth0_client_id
      , and
      com_auth0_domain
      entries exist
    • Incompatible types in callback: Callback type parameters don't match — ensure
      Callback<Credentials, AuthenticationException>
      for login and
      Callback<Void?, AuthenticationException>
      for logout
    • Unresolved
      lifecycleScope
      : Missing dependency — add
      implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.+'
      or move code out of coroutine scope
    • minSdk too low: SDK requires API 21+ — update
      minSdkVersion
      to at least 21
    • Java version mismatch: SDK requires Java 8 — add
      compileOptions
      with
      JavaVersion.VERSION_1_8
    Re-run the build after each fix. Track the number of build-fix iterations.
    Failcheck: If the build still fails after 5–6 fix attempts, stop and ask the user:
    • Question: "The build is still failing after several fix attempts. How would you like to proceed?"
    • Options: "Let the agent continue fixing iteratively" / "I'll fix it manually — show me the errors" / "Skip build verification and proceed"
    Repeat this check after every 5–6 iterations if errors persist. Do not leave the project in a non-compiling state without the user's explicit consent.
    The callback URL must match your Auth0 application settings:
    {SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
  1. 安装SDK:在
    build.gradle
    中添加Auth0 Android SDK依赖:
    gradle
    implementation 'com.auth0.android:auth0:{LATEST_VERSION}'
  2. 配置Auth0
    Agent 指令: 检查用户的提示是否已包含Auth0的Client IDDomain
    • 若两者均已提供,直接使用这些值进入设置指南中的手动设置步骤。
    • 若缺少其中任意一项,在编写代码或文件前必须询问用户:
      • 问题:“您希望如何为该项目配置Auth0?”
      • 选项:“自动设置(推荐)——Auth0 CLI创建应用并将凭证写入strings.xml” / “手动设置——我将提供自己的Client ID和Domain”
    然后根据选择的方式遵循设置指南在确认Auth0凭证前,请勿进入步骤3。
    注意: 对于原生Android应用,Domain和Client ID是公开配置(非机密信息)。无需使用客户端密钥。直接将值写入
    strings.xml
    ,不要在对话输出中显示。
  3. 初始化:创建Auth0账号实例:
    kotlin
    import com.auth0.android.Auth0
    
    val account = Auth0.getInstance(context)
  4. 添加认证UI:通过Web Auth实现登录和登出功能:
    Agent 指令: 在添加新UI元素前,搜索项目中已有的登录、登出按钮点击处理器(例如
    loginButton
    signInButton
    logoutButton
    signOutButton
    或命名与认证相关的
    setOnClickListener
    )。若找到现有处理器,将Auth0代码接入其中,无需修改现有UI。仅当未找到现有处理器时,才创建新按钮。
    登录:
    kotlin
    import com.auth0.android.Auth0
    import com.auth0.android.authentication.AuthenticationAPIClient
    import com.auth0.android.authentication.storage.SecureCredentialsManager
    import com.auth0.android.authentication.storage.SharedPreferencesStorage
    import com.auth0.android.callback.Callback
    import com.auth0.android.authentication.AuthenticationException
    import com.auth0.android.provider.WebAuthProvider
    import com.auth0.android.result.Credentials
    
    val account = Auth0.getInstance(context)
    val authentication = AuthenticationAPIClient(account)
    val storage = SharedPreferencesStorage(context)
    val credentialsManager = SecureCredentialsManager(context, authentication, storage)
    
    WebAuthProvider.login(account)
        .withScheme(getString(R.string.com_auth0_scheme))
        .withScope("openid profile email offline_access")
        .start(this, object : Callback<Credentials, AuthenticationException> {
            override fun onSuccess(result: Credentials) {
                // 用户已认证
                val idToken = result.idToken
                val accessToken = result.accessToken
                // 安全存储凭证
                credentialsManager.saveCredentials(result)
            }
            override fun onFailure(error: AuthenticationException) {
                // 处理认证失败
                Log.e("Auth0", "Authentication failed", error)
            }
        })
    登出:
    kotlin
    WebAuthProvider.logout(account)
        .withScheme(getString(R.string.com_auth0_scheme))
        .start(this, object : Callback<Void?, AuthenticationException> {
            override fun onSuccess(result: Void) {
                // 用户已登出
            }
            override fun onFailure(error: AuthenticationException) {
                Log.e("Auth0", "Logout failed", error)
            }
        })
  5. 构建与验证
    Agent 指令: 完成集成后,构建项目以验证是否编译成功:
    bash
    ./gradlew assembleDebug
    若构建失败,分析错误输出并修复问题。常见的集成构建失败包括:
    • 未解析引用:缺少导入语句——添加所需的
      import com.auth0.android.*
      导入
    • 无法解析符号
      R.string.com_auth0_scheme
      :未更新
      strings.xml
      ——验证其中是否存在
      com_auth0_scheme
      com_auth0_client_id
      com_auth0_domain
      条目
    • 回调中的类型不兼容:回调类型参数不匹配——确保登录使用
      Callback<Credentials, AuthenticationException>
      ,登出使用
      Callback<Void?, AuthenticationException>
    • 未解析
      lifecycleScope
      :缺少依赖——添加
      implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.+'
      或将代码移出协程作用域
    • minSdk版本过低:SDK要求API 21+——将
      minSdkVersion
      更新至至少21
    • Java版本不匹配:SDK要求Java 8——在
      compileOptions
      中添加
      JavaVersion.VERSION_1_8
    每次修复后重新运行构建。记录构建-修复的迭代次数。
    失败检查: 若经过5-6次修复尝试后构建仍失败,请停止并询问用户:
    • 问题:“经过多次修复尝试后,构建仍失败。您希望如何继续?”
    • 选项:“让Agent继续迭代修复” / “我将手动修复——显示错误信息” / “跳过构建验证继续”
    若错误持续存在,每5-6次迭代后重复此检查。未经用户明确同意,请勿让项目处于无法编译的状态。
    回调URL必须与Auth0应用设置匹配:
    {SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback

Detailed Documentation

详细文档

  • Setup Guide — Install SDK, configure Auth0 application, set up callback URLs, Android App Links, custom schemes, ProGuard/R8
  • Integration Patterns — Web Auth login/logout, credential storage, biometric authentication, database login, passwordless authentication, MFA handling, custom tabs, error handling
  • Testing & Reference — Testing checklist, common issues, security considerations, API reference
  • 设置指南——安装SDK、配置Auth0应用、设置回调URL、Android应用链接、自定义Scheme、ProGuard/R8
  • 集成模式——Web Auth登录/登出、凭证存储、生物识别认证、数据库登录、无密码认证、MFA处理、自定义标签页、错误处理
  • 测试与参考——测试清单、常见问题、安全注意事项、API参考

Common Mistakes

常见错误

MistakeFix
App type not set to Native in Auth0 DashboardCreate a Native application type in your Auth0 tenant. The Android SDK requires Native app configuration, not Machine-to-Machine or other types.
Missing callback URL in Allowed Callback URLsAdd
{SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
to your Auth0 application's Allowed Callback URLs setting, where
{SCHEME}
matches
com_auth0_scheme
in
strings.xml
(e.g.,
demo
by default).
Missing
<uses-permission android:name="android.permission.INTERNET" />
Add the INTERNET permission to
AndroidManifest.xml
. The SDK requires network access for authentication.
Custom scheme in lowercaseAndroid requires scheme names to be lowercase. Use
https
(recommended) or lowercase custom scheme like
myapp://callback
.
Forgetting
.validateClaims()
on direct auth calls
Always call
.validateClaims()
when using
AuthenticationAPIClient
directly (for database, passwordless, or API login). Web Auth validates automatically.
Storing tokens in SharedPreferences without encryptionUse
SecureCredentialsManager
to store credentials. Never store tokens manually in plain text. The manager encrypts tokens at rest.
Missing manifest placeholdersAdd
manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "@string/com_auth0_scheme"]
to your
build.gradle
defaultConfig
block.
错误修复方案
Auth0控制台中应用类型未设置为Native在Auth0租户中创建Native类型的应用。Android SDK要求Native应用配置,不支持机器到机器或其他类型。
允许的回调URL中缺少回调URL
{SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
添加到Auth0应用的允许回调URL设置中,其中
{SCHEME}
需与
strings.xml
中的
com_auth0_scheme
匹配(默认例如
demo
)。
缺少
<uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
中添加INTERNET权限。SDK需要网络访问以完成认证。
自定义Scheme为大写Android要求Scheme名称为小写。推荐使用
https
或小写自定义Scheme,如
myapp://callback
直接调用认证接口时忘记
.validateClaims()
使用
AuthenticationAPIClient
直接调用(数据库登录、无密码登录或API登录)时,务必调用
.validateClaims()
。Web Auth会自动验证。
在SharedPreferences中存储令牌时未加密使用
SecureCredentialsManager
存储凭证。切勿手动以明文形式存储令牌。该管理器会在静态存储时加密令牌。
缺少清单占位符
build.gradle
defaultConfig
块中添加
manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "@string/com_auth0_scheme"]

Related Skills

相关技能

Quick Reference

快速参考

Core Classes

核心类

ClassPurpose
Auth0
Entry point for SDK, holds app credentials
WebAuthProvider
OAuth 2.0 login/logout via browser
AuthenticationAPIClient
Direct API calls (database login, passwordless, MFA)
SecureCredentialsManager
Secure storage and retrieval of credentials
Credentials
User tokens and expiration
用途
Auth0
SDK入口点,存储应用凭证
WebAuthProvider
通过浏览器实现OAuth 2.0登录/登出
AuthenticationAPIClient
直接API调用(数据库登录、无密码登录、MFA)
SecureCredentialsManager
安全存储和获取凭证
Credentials
用户令牌和过期信息

Common Use Cases

常见用例

  • Log in with Web Auth
  • Log out
  • Store credentials securely
  • Require biometric authentication
  • Database login
  • Passwordless authentication
  • Handle MFA
  • Call protected APIs
  • 通过Web Auth登录
  • 登出
  • 安全存储凭证
  • 要求生物识别认证
  • 数据库登录
  • 无密码认证
  • 处理MFA
  • 调用受保护的API

References

参考资料