🔐auth0-net-android
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: .NET Android アプリケーションに Auth0 ログインまたはトークン管理を追加する場合。 Auth0.OidcClient.AndroidX を統合します。 ユーザーが「.NET Android アプリにログインを追加したい」と言った場合や、Xamarin Android に言及した場合にも使用してください。
原文を表示
Use when adding Auth0 login or token management to a .NET Android application. Integrates Auth0.OidcClient.AndroidX — use even if the user says "add login to my .NET Android app" or references Xamarin Android.
ユースケース
- ✓.NET Androidアプリにログイン機能を追加するとき
- ✓Auth0認証をAndroidアプリに統合するとき
- ✓Androidアプリのトークン管理を行うとき
- ✓Xamarin Androidプロジェクトにログインを追加するとき
本文(日本語訳)
auth0-net-android インテグレーション
.NET Android アプリケーションに Auth0 認証を追加します。
このスキルは Auth0.OidcClient.AndroidX NuGet パッケージを統合します。
Chrome Custom Tabs を使用した、PKCE 付き OIDC ベースのセキュアなログイン・ログアウトフローを実現します。
Agent への指示: SDK のセットアップ手順を提供する前に、以下のコマンドを実行して最新リリースバージョンを取得してください:
gh api repos/auth0/auth0-oidc-client-net/releases --jq '[.[] | select(.tag_name | startswith("androidx-")) | .tag_name | ltrimstr("androidx-")] | .[0]'以下に記載されているハードコードされたバージョンの代わりに、返されたバージョンをすべての依存関係の記述に使用してください。
前提条件
- .NET 8.0 SDK 以降
- Visual Studio 2022 (17.8+)(.NET Android ワークロードを含む)、または JetBrains Rider
- Android SDK API 21+(最小)、net9.0-android には API 34+ を推奨
- Native アプリケーションが設定済みの Auth0 アカウント
- Node.js 20+(Auth0 CLI による自動セットアップに使用)
使用しない場合
| ユースケース | 推奨スキル |
|---|---|
| .NET MAUI クロスプラットフォームアプリ(iOS + Android + Windows) | auth0-maui |
| .NET iOS 専用アプリ | auth0-net-ios |
| Android 専用 Kotlin アプリ | auth0-android |
| ASP.NET Core サーバーサイド Web アプリ | auth0-aspnetcore-authentication |
| ASP.NET Core Web API(JWT 検証) | auth0-aspnetcore-api |
| React Native モバイルアプリ | auth0-react-native |
クイックスタート手順
Agent への指示: 開始前に、ユーザーのプロジェクトを以下の観点で確認してください:
.csprojファイルのTargetFrameworkから .NET バージョンを特定する- 既存の認証実装を確認する — 既存のログイン・ログアウトハンドラーを検索し、見つかった場合はそれに組み込む(ログインボタンなど既存の UI 要素を再利用し、重複して作成しない)
.csprojまたはAndroidManifest.xmlからプロジェクトの名前空間とパッケージ名を確認する- 重複した設定を避けるため、既存の
Auth0ClientまたはAuth0ClientOptionsの使用箇所を確認する
- SDK のインストール:
dotnet add package Auth0.OidcClient.AndroidX - Auth0 の設定: 自動または手動での設定方法は セットアップガイド を参照してください。
- 認証の組み込み:
Auth0Clientのインスタンス化を追加し、Activity にIntentFilterを設定して、ログイン・ログアウトを UI アクションに紐付けます。 - コールバックの処理:
OnNewIntentをオーバーライドし、ActivityMediator.Instance.Send(intent.DataString)を呼び出して認証フローを完了します。 - ビルドと確認:
dotnet build
Agent への指示: Auth0Client の設定を記述する際は、以下の点に注意してください:
Auth0Clientコンストラクターの第 2 引数としてthis(Activity)を渡すこと。Scope = "openid profile email offline_access"を必ず設定すること —offline_accessスコープはリフレッシュトークンの受け取りに必須であり、ユーザーへの再認証プロンプトなしにサイレントなトークン更新を可能にします。- コールバック URL の形式は
YOUR_ANDROID_PACKAGE_NAME://YOUR_AUTH0_DOMAIN/android/YOUR_ANDROID_PACKAGE_NAME/callback— すべて小文字で記述すること。IntentFilterのDataSchemeは小文字でなければなりません。大文字が含まれると Android がコールバックを受け取れなくなります。- Activity に
LaunchMode = LaunchMode.SingleTaskを設定し、重複インスタンスの生成を防ぐこと。SingleTopは使用しないこと — コールバックリダイレクトを正しく処理できず、Activity のインスタンスが重複して生成されます。- Activity は
Auth0ClientActivityを継承するか、OnNewIntentを手動でオーバーライドしてActivityMediator.Instance.Send(intent.DataString)を呼び出すこと。- トークンは安全に保存すること: ログイン成功後、
AccessTokenとRefreshTokenをSecureStorage(MAUI/Essentials)またはEncryptedSharedPreferences(AndroidX Security —dotnet add package Xamarin.AndroidX.Security.SecurityCryptoが必要)を使用して永続化すること。トークンを平文のSharedPreferencesやインメモリ変数のみに保存しないこと。設定とコードの記述後、ビルドが成功することを確認してください:
dotnet buildビルドが失敗した場合は問題の修正を試みてください。5〜6 回失敗した場合はユーザーにサポートを求めてください。
WebAuth — 認証の仕組み
SDK は Chrome Custom Tabs(システムブラウザー)を通じた WebAuth パターンを使用します。
LoginAsync() が呼び出されると、SDK は以下の手順で動作します:
- PKCE パラメーターを含む
/authorizeURL を構築する - Chrome Custom Tabs で認証 URL を開く
- 認証後、Auth0 がネイティブコールバック URL にリダイレクトする
- Android システムが URL スキームを照合し、
OnNewIntent経由で Activity に届ける ActivityMediatorがトークン交換を完了する
これはネイティブモバイルアプリケーションに推奨される、PKCE 付き標準 OAuth 2.0 認可コードフローです。
コールバック URL の設定
.NET Android のネイティブコールバック URL はパッケージ名をスキームとして使用します。形式は以下のとおりです:
YOUR_ANDROID_PACKAGE_NAME://YOUR_AUTH0_DOMAIN/android/YOUR_ANDROID_PACKAGE_NAME/callback
YOUR_ANDROID_PACKAGE_NAME はアプリケーションのパッケージ名(例: com.mycompany.myapplication)です。
具体例: com.mycompany.myapp://tenant.us.auth0.com/android/com.mycompany.myapp/callback
注意: Auth0 のネイティブ SDK の中には
https://{domain}/android/{package}/callback形式のコールバック URL を使用するものがあります。.NET Android SDK はパッケージ名を URL スキームとして使用する形式を採用しています。
コールバック URL は必ず小文字で記述してください。
この URL は以下の 2 点を満たす必要があります:
- Auth0 ダッシュボードの Allowed Callback URLs および Allowed Logout URLs に登録されていること
- Activity の
IntentFilter属性(DataScheme、DataHost、DataPathPrefix)と一致していること
完了条件
- [ ]
Auth0.OidcClient.AndroidXパッケージがインストール済み(最新の安定バージョン) - [ ]
Auth0Clientが Domain、ClientId、Scope = "openid profile email offline_access"で設定済み - [ ] Activity に
IntentFilterが正しい DataScheme、DataHost、DataPathPrefix で設定済み - [ ] Activity に
LaunchMode = LaunchMode.SingleTaskが設定済み - [ ]
OnNewIntentでActivityMediator.Instance.Send(intent.DataString)が処理済み - [ ] Auth0 ダッシュボードの Allowed Callback URLs および Allowed Logout URLs にコールバック URL が追加済み
- [ ] トークンが安全に保存されている(SecureStorage または EncryptedSharedPreferences)
- [ ] ログイン・ログアウトフローが正常に動作している
- [ ] ビルドがエラーなく成功する
詳細ドキュメント
- セットアップガイド — Auth0 テナントの設定、SDK のインストール、IntentFilter のセットアップ
- インテグレーションパターン — ログイン・ログアウトフロー、トークンアクセス、ユーザープロファイル、エラーハンドリング
- API リファレンスとテスト —
Auth0ClientOptionsの完全なリファレンス、クレーム、テストチェックリスト、トラブルシューティング
よくある間違い
| 間違い | 対処方法 |
|---|---|
| Auth0 ダッシュボードでアプリタイプが Native に設定されていない | ダッシュボードの設定でアプリケーションタイプを「Native」に変更する |
| Auth0 ダッシュボードにコールバック URL が未登録 | yourpackagename://{domain}/android/yourpackagename/callback を Allowed Callback URLs と Allowed Logout URLs の両方に追加する |
DataScheme が小文字でない |
Android はスキームを小文字で要求するため、パッケージ名を小文字で使用すること |
LaunchMode.SingleTask が設定されていない |
重複インスタンスを防ぐため、Activity に LaunchMode = LaunchMode.SingleTask を設定する |
OnNewIntent が処理されていない |
OnNewIntent をオーバーライドして ActivityMediator.Instance.Send(intent.DataString) を呼び出す |
Domain に https:// プレフィックスを使用している |
Domain はホスト名のみを指定すること(例: tenant.auth0.com。https://tenant.auth0.com は不可) |
| Auth0Client に Activity コンテキストを渡していない | 第 2 引数として this を渡す: new Auth0Client(options, this) |
| IntentFilter の DataHost / DataPathPrefix が一致していない | DataHost が Auth0 ドメインと一致し、DataPathPrefix が /android/yourpackagename/callback になっていることを確認する |
offline_access スコープが欠けている |
サイレント更新用のリフレッシュトークンを受け取るため、Scope に必ず offline_access を含める |
LaunchMode.SingleTask の代わりに LaunchMode.SingleTop を使用している |
LaunchMode.SingleTask を使用すること — SingleTop は Auth0 コールバックリダイレクトを正しく処理できない |
| トークンを平文の SharedPreferences に保存している | AndroidX Security ライブラリの SecureStorage または EncryptedSharedPreferences を使用すること |
テストに関する注意事項
Agent への指示: エミュレーターに加えて実機でのテストを行うようユーザーに促してください。WebAuth の一部の動作(Chrome Custom Tabs、URL スキームのインターセプト)は、実機とエミュレーターで異なる場合があります。リリース前に実際のハードウェアでログイン → コールバック → トークン取得の完全なフローをテストしてください。
実機テスト項目:
- ログインフロー: Chrome Custom Tab が開く → 認証 → アプリに戻る
- コールバック:
OnNewIntentが正しい Intent データで発火する - ログアウトフロー: ブラウザーが開く → セッションがクリアされる → アプリに戻る
- キャンセル: ユーザーが戻るボタンを押す → アプリが
UserCancelを適切に処理する
関連スキル
- auth0-maui — .NET MAUI クロスプラットフォームアプリ(iOS + Android + Windows)
- auth0-net-ios — .NET iOS 専用アプリ
- auth0-android — Android ネイティブ Kotlin アプリ
- auth0-aspnetcore-authentication — ASP.NET Core サーバーサイド Web アプリ
- auth0-aspnetcore-api — JWT 検証付き ASP.NET Core Web API
クイックリファレンス
using Auth0.OidcClient;
var client = new Auth0Client(new Auth0ClientOptions
{
Domain = "YOUR_AUTH0_DOMAIN",
ClientId = "YOUR_AUTH0_CLIENT_ID",
Scope = "openid profile email offline_access"
}, this);
ログイン
var loginResult = await client.LoginAsync();
エラー処理
var loginResult = await client.LoginAsync();
if (loginResult.IsError)
{
Debug.WriteLine($"An error occurred during login: {loginResult.Error}");
}
アクセストークン
var loginResult = await client.LoginAsync();
if (!loginResult.IsError)
{
Debug.WriteLine($"Authentication successful.");
}
ユーザー情報
if (!loginResult.IsError)
{
Debug.WriteLine($"name: {loginResult.User.FindFirst(c => c.Type == "name")?.Value}");
Debug.WriteLine($"email: {loginResult.User.FindFirst(c => c.Type == "email")?.Value}");
}
すべてのクレームの一覧表示
if (!login
原文(English)を表示
auth0-net-android Integration
Add Auth0 authentication to .NET Android applications. This skill integrates the Auth0.OidcClient.AndroidX NuGet package which uses Chrome Custom Tabs for secure OIDC-based login and logout flows with PKCE.
Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:
gh api repos/auth0/auth0-oidc-client-net/releases --jq '[.[] | select(.tag_name | startswith("androidx-")) | .tag_name | ltrimstr("androidx-")] | .[0]'Use the returned version in all dependency lines instead of any hardcoded version below.
Prerequisites
- .NET 8.0 SDK or later
- Visual Studio 2022 (17.8+) with .NET Android workload, or JetBrains Rider
- Android SDK API 21+ (minimum), API 34+ recommended for net9.0-android
- Auth0 account with a Native application configured
- Node.js 20+ (for Auth0 CLI automated setup)
When NOT to Use
| Use Case | Recommended Skill |
|---|---|
| .NET MAUI cross-platform app (iOS + Android + Windows) | auth0-maui |
| .NET iOS-only app | auth0-net-ios |
| Android-only Kotlin app | auth0-android |
| ASP.NET Core server-side web app | auth0-aspnetcore-authentication |
| ASP.NET Core Web API (JWT validation) | auth0-aspnetcore-api |
| React Native mobile app | auth0-react-native |
Quick Start Workflow
Agent instruction: Before starting, examine the user's project:
- Identify the .NET version from the
.csprojfile (TargetFramework)- Check for existing authentication implementations — search for existing login/logout handlers and hook into them if found (reuse existing UI elements like login buttons rather than creating duplicates)
- Note the project's namespace and package name from the
.csprojorAndroidManifest.xml- Look for existing
Auth0ClientorAuth0ClientOptionsusage to avoid duplicate configuration
- Install SDK:
dotnet add package Auth0.OidcClient.AndroidX - Configure Auth0: See Setup Guide for automatic or manual configuration.
- Integrate authentication: Add
Auth0Clientinstantiation, configure theIntentFilteron your Activity, and wire login/logout to UI actions. - Handle callback: Override
OnNewIntentand callActivityMediator.Instance.Send(intent.DataString)to complete the authentication flow. - Build and verify:
dotnet build
Agent instruction: When writing the Auth0Client configuration:
- Pass
this(the Activity) as the second argument toAuth0Clientconstructor.- Always set
Scope = "openid profile email offline_access"— theoffline_accessscope is required to receive refresh tokens, enabling silent token renewal without re-prompting the user.- The callback URL format is
YOUR_ANDROID_PACKAGE_NAME://YOUR_AUTH0_DOMAIN/android/YOUR_ANDROID_PACKAGE_NAME/callback— all lowercase.- The
DataSchemein theIntentFiltermust be lowercase or Android will not receive callbacks.- Set
LaunchMode = LaunchMode.SingleTaskon the Activity to prevent duplicate instances. Do NOT useSingleTop— it does not correctly handle the callback redirect and will create duplicate Activity instances.- The Activity should either extend
Auth0ClientActivityOR manually overrideOnNewIntentand callActivityMediator.Instance.Send(intent.DataString).- Store tokens securely: After successful login, persist
AccessTokenandRefreshTokenusingSecureStorage(MAUI/Essentials) orEncryptedSharedPreferences(AndroidX Security — requiresdotnet add package Xamarin.AndroidX.Security.SecurityCrypto). Never store tokens in plainSharedPreferencesor in-memory variables only.After writing configuration and code, verify the build succeeds:
dotnet buildIf the build fails, attempt to fix the issue. After 5-6 failed attempts, ask the user for help.
WebAuth — How Authentication Works
The SDK uses the WebAuth pattern via Chrome Custom Tabs (the system browser). When LoginAsync() is called, the SDK:
- Constructs the
/authorizeURL with PKCE parameters - Opens Chrome Custom Tabs with the authorization URL
- After authentication, Auth0 redirects to the native callback URL
- The Android system matches the URL scheme and delivers it to your Activity via
OnNewIntent ActivityMediatorcompletes the token exchange
This is the standard OAuth 2.0 Authorization Code flow with PKCE, recommended for native mobile applications.
Callback URL Configuration
The native callback URL for .NET Android uses the package name as the scheme. The format is:
YOUR_ANDROID_PACKAGE_NAME://YOUR_AUTH0_DOMAIN/android/YOUR_ANDROID_PACKAGE_NAME/callback
Where YOUR_ANDROID_PACKAGE_NAME is the Package Name for your application, such as com.mycompany.myapplication. For example: com.mycompany.myapp://tenant.us.auth0.com/android/com.mycompany.myapp/callback.
Note: Some Auth0 native SDKs use
https://{domain}/android/{package}/callbackas the callback URL format. The .NET Android SDK uses the package name as the URL scheme instead.
Ensure that the Callback URL is in lowercase.
This URL must be:
- Registered in Auth0 Dashboard under Allowed Callback URLs and Allowed Logout URLs
- Matched by the
IntentFilterattributes (DataScheme,DataHost,DataPathPrefix) on your Activity
Done When
- [ ]
Auth0.OidcClient.AndroidXpackage installed (latest stable version) - [ ]
Auth0Clientconfigured with Domain, ClientId, andScope = "openid profile email offline_access" - [ ]
IntentFilterconfigured on Activity with correct DataScheme, DataHost, DataPathPrefix - [ ]
LaunchMode = LaunchMode.SingleTaskset on Activity - [ ]
OnNewIntenthandled withActivityMediator.Instance.Send(intent.DataString) - [ ] Callback URL added to Auth0 Dashboard Allowed Callback URLs and Allowed Logout URLs
- [ ] Tokens stored securely (SecureStorage or EncryptedSharedPreferences)
- [ ] Login/logout flow working
- [ ] Build succeeds with no errors
Detailed Documentation
- Setup Guide — Auth0 tenant configuration, SDK installation, IntentFilter setup
- Integration Patterns — Login/logout flows, token access, user profile, error handling
- API Reference & Testing — Full
Auth0ClientOptionsreference, claims, testing checklist, troubleshooting
Common Mistakes
| Mistake | Fix |
|---|---|
| App type not set to Native in Auth0 Dashboard | Change application type to "Native" in Dashboard settings |
| Missing callback URL in Auth0 Dashboard | Add yourpackagename://{domain}/android/yourpackagename/callback to Allowed Callback URLs AND Allowed Logout URLs |
DataScheme not lowercase |
Android requires the scheme to be lowercase — use lowercase package name |
Missing LaunchMode.SingleTask |
Set LaunchMode = LaunchMode.SingleTask on the Activity to prevent duplicate instances |
Not handling OnNewIntent |
Override OnNewIntent and call ActivityMediator.Instance.Send(intent.DataString) |
Using https:// prefix in Domain |
Domain should be hostname only (e.g., tenant.auth0.com, not https://tenant.auth0.com) |
| Not passing Activity context to Auth0Client | Pass this as second parameter: new Auth0Client(options, this) |
| IntentFilter DataHost/DataPathPrefix mismatch | Ensure DataHost matches your Auth0 domain and DataPathPrefix is /android/yourpackagename/callback |
Missing offline_access scope |
Always include offline_access in Scope to receive refresh tokens for silent renewal |
Using LaunchMode.SingleTop instead of SingleTask |
Must use LaunchMode.SingleTask — SingleTop does not correctly handle the Auth0 callback redirect |
| Storing tokens in plain SharedPreferences | Use SecureStorage or EncryptedSharedPreferences from AndroidX Security library |
Testing Notes
Agent instruction: Remind the user to test on a physical device in addition to emulators. Some WebAuth behaviors (Chrome Custom Tabs, URL scheme interception) may differ on physical devices vs. emulators. Test the full login → callback → token flow on real hardware before shipping.
Physical Device Testing:
- Login flow: Chrome Custom Tab opens → authenticate → returns to app
- Callback:
OnNewIntentfires with correct intent data - Logout flow: Browser opens → session cleared → returns to app
- Cancel: User presses back → app handles
UserCancelgracefully
Related Skills
- auth0-maui — .NET MAUI cross-platform apps (iOS + Android + Windows)
- auth0-net-ios — .NET iOS-only apps
- auth0-android — Android-native Kotlin apps
- auth0-aspnetcore-authentication — ASP.NET Core server-side web apps
- auth0-aspnetcore-api — ASP.NET Core Web API with JWT validation
Quick Reference
using Auth0.OidcClient;
var client = new Auth0Client(new Auth0ClientOptions
{
Domain = "YOUR_AUTH0_DOMAIN",
ClientId = "YOUR_AUTH0_CLIENT_ID",
Scope = "openid profile email offline_access"
}, this);
Login
var loginResult = await client.LoginAsync();
Handle Errors
var loginResult = await client.LoginAsync();
if (loginResult.IsError)
{
Debug.WriteLine($"An error occurred during login: {loginResult.Error}");
}
Access Tokens
var loginResult = await client.LoginAsync();
if (!loginResult.IsError)
{
Debug.WriteLine($"Authentication successful.");
}
User Information
if (!loginResult.IsError)
{
Debug.WriteLine($"name: {loginResult.User.FindFirst(c => c.Type == "name")?.Value}");
Debug.WriteLine($"email: {loginResult.User.FindFirst(c => c.Type == "email")?.Value}");
}
List All Claims
if (!loginResult.IsError)
{
foreach (var claim in loginResult.User.Claims)
{
Debug.WriteLine($"{claim.Type} = {claim.Value}");
}
}
Logout
BrowserResultType browserResult = await client.LogoutAsync();
Activity with IntentFilter (Required)
[Activity(Label = "AndroidSample", MainLauncher = true, Icon = "@drawable/icon",
LaunchMode = LaunchMode.SingleTask)]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataScheme = "YOUR_ANDROID_PACKAGE_NAME",
DataHost = "YOUR_AUTH0_DOMAIN",
DataPathPrefix = "/android/YOUR_ANDROID_PACKAGE_NAME/callback")]
public class MainActivity : Activity
{
// Code omitted
}
Handle Callback in OnNewIntent (Required)
protected override async void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
Auth0.OidcClient.ActivityMediator.Instance.Send(intent.DataString);
}
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。