🔐auth0-android
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: KotlinまたはJavaのAndroidアプリに、Auth0のログイン・ログアウト・認証情報管理を追加する場合。 Web Auth、生体認証で保護されたCredentialsManager、MFAに対応しており、ユーザーが「Androidアプリにログイン機能を追加したい」とだけ言ってAuth0に言及しない場合にも適用されます。 `com.auth0.android:auth0` ライブラリを統合します。
原文を表示
Use when adding Auth0 login, logout, or credential management to an Android app in Kotlin or Java. Covers Web Auth, biometric-protected CredentialsManager, and MFA — even if the user just says "add login to my Android app" without mentioning Auth0. Integrates com.auth0.android:auth0.
ユースケース
- ✓AndroidアプリにAuth0のログイン機能を追加するとき
- ✓ログアウト・認証情報管理を実装するとき
- ✓Web Authで保護されたログインを導入するとき
- ✓生体認証対応のCredentialsManagerを追加するとき
- ✓MFA機能をAndroidアプリに組み込むとき
本文(日本語訳)
Auth0 Android インテグレーション
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 を確認してください。
前提条件
- Android API 21 以上
- Kotlin または Java プロジェクト
- Native アプリケーションが設定済みの Auth0 アカウント
- Auth0 がまだセットアップされていない場合は、auth0-quickstart を参照してください
使用しない場面
- React Native アプリ: auth0-react-native を使用してください
- Flutter アプリ: Flutter ネイティブの Auth0 SDK を使用してください
- Web SPA(React、Angular、Vue): auth0-react、auth0-angular、または auth0-vue を使用してください
- Node.js/Express サーバー: auth0-express を使用してください
- iOS/macOS アプリ: auth0-swift を使用してください
クイックスタート手順
-
SDKのインストール:
build.gradleに Auth0 Android SDK の依存関係を追加します:implementation 'com.auth0.android:auth0:{LATEST_VERSION}' -
Auth0の設定:
Agentへの指示: ユーザーのプロンプトに Auth0 の Client ID と Domain の両方が含まれているか確認してください。
- 両方が提供されている場合は、それらの値を使用して セットアップガイド の Manual Setup に直接進んでください。
- どちらかが不足している場合は、コードやファイルを一切記述する前に、ユーザーに必ず確認してください:
- 質問: 「このプロジェクトの Auth0 をどのように設定しますか?」
- 選択肢: 「自動セットアップ(推奨)— Auth0 CLI がアプリを作成し、credentials を strings.xml に書き込みます」 / 「手動セットアップ — Client ID と Domain を自分で入力します」
その後、選択したパスに従って セットアップガイド を参照してください。 Auth0 の credentials が確認されるまで、ステップ 3 に進まないでください。
注意: ネイティブ Android アプリの場合、Domain と Client ID はパブリックな設定情報であり(シークレットではありません)、クライアントシークレットは使用しません。値は会話の出力に表示せず、直接
strings.xmlに書き込んでください。 -
初期化: Auth0 アカウントインスタンスを作成します:
import com.auth0.android.Auth0 val account = Auth0.getInstance(context)重要:
Auth0.getInstance(context)はstrings.xmlからcom_auth0_client_idとcom_auth0_domainを自動的に読み込みます。clientIdやdomainを引数として渡す(例:Auth0.getInstance(clientId, domain))のは絶対に避けてください — credentials がソースコードにハードコードされてしまいます。 -
認証UIの追加: Web Auth を使用してログインとログアウトを実装します:
Agentへの指示: 新しいUI要素を追加する前に、プロジェクト内でログイン・ログアウト・サインイン・サインアウトボタンの既存のクリックハンドラー(例:
loginButton、signInButton、logoutButton、signOutButton、または認証関連の命名を持つsetOnClickListener)を検索してください。既存のハンドラーが見つかった場合は、既存のUIを変更せずに Auth0 のコードをそこに組み込んでください。既存のハンドラーが見つからない場合にのみ、新しいボタンを作成してください。ログイン:
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 // credentials を安全に保存 credentialsManager.saveCredentials(result) } override fun onFailure(error: AuthenticationException) { // 認証失敗の処理 Log.e("Auth0", "Authentication failed", error) } })ログアウト:
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) } }) -
ビルドと確認:
Agentへの指示: インテグレーション完了後、プロジェクトをビルドして正常にコンパイルされることを確認してください:
./gradlew assembleDebugビルドが失敗した場合は、エラー出力を分析して問題を修正してください。インテグレーション時によくあるビルドエラーには以下が含まれます:
- 未解決の参照: import 文の不足 — 必要な
import com.auth0.android.*の import を追加してください 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 - 未解決の参照: import 文の不足 — 必要な
詳細ドキュメント
- セットアップガイド — SDK のインストール、Auth0 アプリケーションの設定、コールバック URL のセットアップ、Android App Links、カスタムスキーム、ProGuard/R8
- インテグレーションパターン — Web Auth によるログイン/ログアウト、credential のストレージ、生体認証、データベースログイン、パスワードレス認証、MFA 処理、カスタムタブ、エラーハンドリング
- テストとリファレンス — テストチェックリスト、よくある問題、セキュリティに関する考慮事項、API リファレンス
よくある間違い
| 間違い | 修正方法 |
|---|---|
| Auth0 ダッシュボードでアプリタイプが Native に設定されていない | Auth0 テナントで Native アプリケーションタイプを作成してください。Android SDK は Native アプリの設定を必要とし、Machine-to-Machine などの他のタイプは使用できません。 |
| Allowed Callback URLs にコールバック URL が設定されていない | Auth0 アプリケーションの Allowed Callback URLs 設定に {SCHEME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback を追加してください。{SCHEME} は strings.xml の com_auth0_scheme(デフォルトは demo)と一致する必要があります。 |
<uses-permission android:name="android.permission.INTERNET" /> が不足している |
AndroidManifest.xml に INTERNET パーミッションを追加してください。SDK は認証のためにネットワークアクセスを必要とします。 |
| カスタムスキームが小文字でない | Android ではスキーム名を小文字にする必要があります。https(推奨)または myapp://callback のような小文字のカスタムスキームを使用してください。 |
直接認証呼び出しで .validateClaims() を忘れている |
AuthenticationAPIClient を直接使用する場合(データベース、パスワードレス、API ログイン)は、常に .validateClaims() を呼び出してください。Web Auth は自動的に検証します。 |
| 暗号化なしで SharedPreferences にトークンを保存している | credentials の保存には SecureCredentialsManager を使用してください。トークンを平文で手動保存しないでください。このマネージャーはトークンを保存時に暗号化します。 |
| マニフェストプレースホルダーの設定漏れ | build.gradle の defaultConfig ブロックに manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "@string/com_auth0_scheme"] を追加してください。 |
関連 Skill
- auth0-quickstart — Auth0 アカウントとアプリケーションのセットアップ
- auth0-mfa — 多要素認証の設定
- auth0-swift — iOS/macOS 認証
- auth0-cli — ターミナルから Auth0 リソースを管理
クイックリファレンス
コアクラス
| クラス | 用途 |
|---|---|
Auth0 |
SDK のエントリーポイント。アプリの credentials を保持します |
WebAuthProvider |
ブラウザを経由した OAuth 2.0 によるログイン/ログアウト |
AuthenticationAPIClient |
直接 API 呼び出し(データベースログイン、パスワードレス、MFA) |
SecureCredentialsManager |
credentials の安全な保存と取得 |
Credentials |
ユーザートークンと有効期限 |
主なユースケース
参考リンク
- [Auth0 Android SDK ドキュメント](https://auth0.com
原文(English)を表示
Auth0 Android Integration
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
implementationdependency lines instead of any hardcoded version below. If the command fails, fall back to checking 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
When NOT to Use
- React Native apps: Use auth0-react-native
- Flutter apps: Use the native Flutter Auth0 SDK
- Web SPAs (React, Angular, Vue): Use auth0-react, auth0-angular, or auth0-vue
- Node.js/Express servers: Use auth0-express
- iOS/macOS apps: Use auth0-swift
Quick Start Workflow
-
Install SDK: Add the Auth0 Android SDK dependency to your
build.gradle:implementation 'com.auth0.android:auth0:{LATEST_VERSION}' -
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.xmlwithout displaying them in conversation output. -
Initialize: Create an Auth0 account instance:
import com.auth0.android.Auth0 val account = Auth0.getInstance(context)IMPORTANT:
Auth0.getInstance(context)auto-readscom_auth0_client_idandcom_auth0_domainfromstrings.xml. Never passclientIdordomainas arguments (e.g.Auth0.getInstance(clientId, domain)) — that hardcodes credentials in source. -
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, orsetOnClickListenerwith 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:
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:
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) } }) -
Build & Verify:
Agent instruction: After completing the integration, build the project to verify it compiles successfully:
./gradlew assembleDebugIf 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.xmlnot updated — verifycom_auth0_scheme,com_auth0_client_id, andcom_auth0_domainentries exist - Incompatible types in callback: Callback type parameters don't match — ensure
Callback<Credentials, AuthenticationException>for login andCallback<Void?, AuthenticationException>for logout - Unresolved
lifecycleScope: Missing dependency — addimplementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.+'or move code out of coroutine scope - minSdk too low: SDK requires API 21+ — update
minSdkVersionto at least 21 - Java version mismatch: SDK requires Java 8 — add
compileOptionswithJavaVersion.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 - Unresolved reference: Missing import statements — add the required
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
Common Mistakes
| Mistake | Fix |
|---|---|
| App type not set to Native in Auth0 Dashboard | Create 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 URLs | Add {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 lowercase | Android 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 encryption | Use SecureCredentialsManager to store credentials. Never store tokens manually in plain text. The manager encrypts tokens at rest. |
| Missing manifest placeholders | Add manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "@string/com_auth0_scheme"] to your build.gradle defaultConfig block. |
Related Skills
- auth0-quickstart — Set up an Auth0 account and application
- auth0-mfa — Configure multi-factor authentication
- auth0-swift — iOS/macOS authentication
- auth0-cli — Manage Auth0 resources from the terminal
Quick Reference
Core Classes
| Class | Purpose |
|---|---|
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 |
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
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。