auth0-net-android

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

auth0-net-android Integration

auth0-net-android集成

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:
bash
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.
为.NET Android应用添加Auth0认证功能。此技能集成
Auth0.OidcClient.AndroidX
NuGet包,该包使用Chrome Custom Tabs实现基于OIDC的安全登录和登出流程,并采用PKCE机制。
Agent指令: 在提供SDK设置说明之前,运行以下命令获取最新版本:
bash
gh api repos/auth0/auth0-oidc-client-net/releases --jq '[.[] | select(.tag_name | startswith("androidx-")) | .tag_name | ltrimstr("androidx-")] | .[0]'
在所有依赖项代码行中使用返回的版本,而非下方任何硬编码版本。

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)
  • .NET 8.0 SDK或更高版本
  • 安装了.NET Android工作负载的Visual Studio 2022(17.8+),或JetBrains Rider
  • Android SDK API 21+(最低要求),net9.0-android推荐使用API 34+
  • 已配置Native应用的Auth0账户
  • Node.js 20+(用于Auth0 CLI自动化设置)

When NOT to Use

不适用于以下场景

Use CaseRecommended 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
使用场景推荐技能
.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

Quick Start Workflow

快速开始流程

Agent instruction: Before starting, examine the user's project:
  1. Identify the .NET version from the
    .csproj
    file (
    TargetFramework
    )
  2. 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)
  3. Note the project's namespace and package name from the
    .csproj
    or
    AndroidManifest.xml
  4. Look for existing
    Auth0Client
    or
    Auth0ClientOptions
    usage to avoid duplicate configuration
  1. Install SDK:
    dotnet add package Auth0.OidcClient.AndroidX
  2. Configure Auth0: See Setup Guide for automatic or manual configuration.
  3. Integrate authentication: Add
    Auth0Client
    instantiation, configure the
    IntentFilter
    on your Activity, and wire login/logout to UI actions.
  4. Handle callback: Override
    OnNewIntent
    and call
    ActivityMediator.Instance.Send(intent.DataString)
    to complete the authentication flow.
  5. Build and verify:
    dotnet build
Agent instruction: When writing the Auth0Client configuration:
  • Pass
    this
    (the Activity) as the second argument to
    Auth0Client
    constructor.
  • Always set
    Scope = "openid profile email offline_access"
    — the
    offline_access
    scope 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
    DataScheme
    in the
    IntentFilter
    must be lowercase or Android will not receive callbacks.
  • Set
    LaunchMode = LaunchMode.SingleTask
    on the Activity to prevent duplicate instances. Do NOT use
    SingleTop
    — it does not correctly handle the callback redirect and will create duplicate Activity instances.
  • The Activity should either extend
    Auth0ClientActivity
    OR manually override
    OnNewIntent
    and call
    ActivityMediator.Instance.Send(intent.DataString)
    .
  • Store tokens securely: After successful login, persist
    AccessToken
    and
    RefreshToken
    using
    SecureStorage
    (MAUI/Essentials) or
    EncryptedSharedPreferences
    (AndroidX Security — requires
    dotnet add package Xamarin.AndroidX.Security.SecurityCrypto
    ). Never store tokens in plain
    SharedPreferences
    or in-memory variables only.
After writing configuration and code, verify the build succeeds:
bash
dotnet build
If the build fails, attempt to fix the issue. After 5-6 failed attempts, ask the user for help.
Agent指令: 开始前,请检查用户项目:
  1. .csproj
    文件的
    TargetFramework
    字段识别.NET版本
  2. 检查现有认证实现——搜索已有的登录/登出处理程序,若存在则接入(重用现有UI元素如登录按钮,避免创建重复元素)
  3. 记录
    .csproj
    AndroidManifest.xml
    中的项目命名空间和包名
  4. 查找是否已有
    Auth0Client
    Auth0ClientOptions
    的使用,避免重复配置
  1. 安装SDK
    dotnet add package Auth0.OidcClient.AndroidX
  2. 配置Auth0:参考设置指南进行自动或手动配置。
  3. 集成认证功能:实例化
    Auth0Client
    ,在Activity上配置
    IntentFilter
    ,并将登录/登出操作关联到UI事件。
  4. 处理回调:重写
    OnNewIntent
    并调用
    ActivityMediator.Instance.Send(intent.DataString)
    以完成认证流程。
  5. 构建并验证
    dotnet build
Agent指令: 编写Auth0Client配置时:
  • this
    (当前Activity)作为
    Auth0Client
    构造函数的第二个参数传入。
  • 务必设置
    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)
  • 安全存储令牌:登录成功后,使用
    SecureStorage
    (MAUI/Essentials)或
    EncryptedSharedPreferences
    (AndroidX Security——需安装
    dotnet add package Xamarin.AndroidX.Security.SecurityCrypto
    )持久化存储
    AccessToken
    RefreshToken
    。绝不要将令牌存储在明文
    SharedPreferences
    或仅存于内存变量中。
编写完配置和代码后,验证构建是否成功:
bash
dotnet build
若构建失败,尝试修复问题。经过5-6次失败尝试后,请向用户寻求帮助。

WebAuth — How Authentication Works

WebAuth——认证工作原理

The SDK uses the WebAuth pattern via Chrome Custom Tabs (the system browser). When
LoginAsync()
is called, the SDK:
  1. Constructs the
    /authorize
    URL with PKCE parameters
  2. Opens Chrome Custom Tabs with the authorization URL
  3. After authentication, Auth0 redirects to the native callback URL
  4. The Android system matches the URL scheme and delivers it to your Activity via
    OnNewIntent
  5. ActivityMediator
    completes the token exchange
This is the standard OAuth 2.0 Authorization Code flow with PKCE, recommended for native mobile applications.
SDK通过Chrome Custom Tabs(系统浏览器)采用WebAuth模式。调用
LoginAsync()
时,SDK会:
  1. 构造包含PKCE参数的
    /authorize
    URL
  2. 使用授权URL打开Chrome Custom Tabs
  3. 认证完成后,Auth0重定向到原生回调URL
  4. Android系统匹配URL scheme并通过
    OnNewIntent
    将其传递给你的Activity
  5. ActivityMediator
    完成令牌交换
这是适用于原生移动应用的标准OAuth 2.0授权码流程(带PKCE)。

Callback URL Configuration

回调URL配置

The native callback URL for .NET Android uses the package name as the scheme. The format is:
text
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}/callback
as 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:
  1. Registered in Auth0 Dashboard under Allowed Callback URLs and Allowed Logout URLs
  2. Matched by the
    IntentFilter
    attributes (
    DataScheme
    ,
    DataHost
    ,
    DataPathPrefix
    ) on your Activity
.NET Android的原生回调URL使用包名作为scheme,格式如下:
text
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 scheme。
确保回调URL为小写。
此URL必须:
  1. 在Auth0控制台的允许回调URL允许登出URL中注册
  2. 与Activity上的
    IntentFilter
    属性(
    DataScheme
    DataHost
    DataPathPrefix
    )匹配

Done When

完成标准

  • Auth0.OidcClient.AndroidX
    package installed (latest stable version)
  • Auth0Client
    configured with Domain, ClientId, and
    Scope = "openid profile email offline_access"
  • IntentFilter
    configured on Activity with correct DataScheme, DataHost, DataPathPrefix
  • LaunchMode = LaunchMode.SingleTask
    set on Activity
  • OnNewIntent
    handled with
    ActivityMediator.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
  • 已安装
    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)
  • 回调URL已添加到Auth0控制台的允许回调URL和允许登出URL
  • 令牌已安全存储(使用SecureStorage或EncryptedSharedPreferences)
  • 登录/登出流程可正常工作
  • 构建无错误

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
    Auth0ClientOptions
    reference, claims, testing checklist, troubleshooting
  • 设置指南 —— Auth0租户配置、SDK安装、IntentFilter设置
  • 集成模式 —— 登录/登出流程、令牌访问、用户信息、错误处理
  • API参考与测试 ——
    Auth0ClientOptions
    完整参考、声明、测试清单、故障排除

Common Mistakes

常见错误

MistakeFix
App type not set to Native in Auth0 DashboardChange application type to "Native" in Dashboard settings
Missing callback URL in Auth0 DashboardAdd
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 Auth0ClientPass
this
as second parameter:
new Auth0Client(options, this)
IntentFilter DataHost/DataPathPrefix mismatchEnsure 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 SharedPreferencesUse
SecureStorage
or
EncryptedSharedPreferences
from AndroidX Security library
错误修复方案
Auth0控制台中应用类型未设置为Native在控制台设置中将应用类型更改为“Native”
Auth0控制台中缺少回调URL
yourpackagename://{domain}/android/yourpackagename/callback
添加到允许回调URL和允许登出URL
DataScheme
未小写
Android要求scheme为小写——使用小写包名
缺少
LaunchMode.SingleTask
在Activity上设置
LaunchMode = LaunchMode.SingleTask
以避免重复实例
未处理
OnNewIntent
重写
OnNewIntent
并调用
ActivityMediator.Instance.Send(intent.DataString)
Domain使用
https://
前缀
Domain应仅为主机名(例如
tenant.auth0.com
,而非
https://tenant.auth0.com
未将Activity上下文传递给Auth0Client
this
作为第二个参数传入:
new Auth0Client(options, this)
IntentFilter的DataHost/DataPathPrefix不匹配确保DataHost与你的Auth0域名匹配,DataPathPrefix为
/android/yourpackagename/callback
缺少
offline_access
作用域
务必在Scope中包含
offline_access
以获取刷新令牌,支持静默更新
使用
LaunchMode.SingleTop
而非
SingleTask
必须使用
LaunchMode.SingleTask
——
SingleTop
无法正确处理Auth0回调重定向
将令牌存储在明文SharedPreferences中使用AndroidX Security库的
SecureStorage
EncryptedSharedPreferences

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:
    OnNewIntent
    fires with correct intent data
  • Logout flow: Browser opens → session cleared → returns to app
  • Cancel: User presses back → app handles
    UserCancel
    gracefully
Agent指令: 提醒用户除模拟器外,还需在物理设备上测试。部分WebAuth行为(Chrome Custom Tabs、URL scheme拦截)在物理设备和模拟器上可能存在差异。发布前请在真实硬件上测试完整的登录→回调→令牌流程。
物理设备测试:
  • 登录流程:Chrome Custom Tab打开→认证→返回应用
  • 回调:
    OnNewIntent
    触发并携带正确的intent数据
  • 登出流程:浏览器打开→会话清除→返回应用
  • 取消:用户按返回键→应用优雅处理
    UserCancel

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
  • 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

Quick Reference

快速参考

csharp
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);
csharp
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

登录

csharp
var loginResult = await client.LoginAsync();
csharp
var loginResult = await client.LoginAsync();

Handle Errors

错误处理

csharp
var loginResult = await client.LoginAsync();

if (loginResult.IsError)
{
    Debug.WriteLine($"An error occurred during login: {loginResult.Error}");
}
csharp
var loginResult = await client.LoginAsync();

if (loginResult.IsError)
{
    Debug.WriteLine($"登录过程中发生错误:{loginResult.Error}");
}

Access Tokens

访问令牌

csharp
var loginResult = await client.LoginAsync();

if (!loginResult.IsError)
{
    Debug.WriteLine($"Authentication successful.");
}
csharp
var loginResult = await client.LoginAsync();

if (!loginResult.IsError)
{
    Debug.WriteLine($"认证成功。");
}

User Information

用户信息

csharp
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}");
}
csharp
if (!loginResult.IsError)
{
    Debug.WriteLine($"姓名: {loginResult.User.FindFirst(c => c.Type == "name")?.Value}");
    Debug.WriteLine($"邮箱: {loginResult.User.FindFirst(c => c.Type == "email")?.Value}");
}

List All Claims

列出所有声明

csharp
if (!loginResult.IsError)
{
    foreach (var claim in loginResult.User.Claims)
    {
        Debug.WriteLine($"{claim.Type} = {claim.Value}");
    }
}
csharp
if (!loginResult.IsError)
{
    foreach (var claim in loginResult.User.Claims)
    {
        Debug.WriteLine($"{claim.Type} = {claim.Value}");
    }
}

Logout

登出

csharp
BrowserResultType browserResult = await client.LogoutAsync();
csharp
BrowserResultType browserResult = await client.LogoutAsync();

Activity with IntentFilter (Required)

带IntentFilter的Activity(必填)

csharp
[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
}
csharp
[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
{
    // 代码省略
}

Handle Callback in OnNewIntent (Required)

在OnNewIntent中处理回调(必填)

csharp
protected override async void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);

    Auth0.OidcClient.ActivityMediator.Instance.Send(intent.DataString);
}
csharp
protected override async void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);

    Auth0.OidcClient.ActivityMediator.Instance.Send(intent.DataString);
}

References

参考链接