> ## Documentation Index
> Fetch the complete documentation index at: https://auth0-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Login to Your .NET Android & iOS Application

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

<HowToSchema />

<Accordion title="Use AI to integrate Auth0" icon="microchip-ai" iconType="solid" defaultOpen>
  If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 authentication automatically in minutes using [agent skills](https://agentskills.io/home).

  **Install:**

  ```bash theme={null}
  npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-net-android --skill auth0-net-ios
  ```

  **Then ask your AI assistant:**

  ```text theme={null}
  Add Auth0 authentication to my .NET Android & iOS app
  ```

  Your AI assistant will automatically create your Auth0 application, fetch credentials, install the Auth0 OidcClient SDK, configure platform-specific settings, and implement login/logout flows. [Full agent skills documentation →](/docs/quickstart/agent-skills)
</Accordion>

## Get Started

<Steps>
  <Step title="Create a new .NET project" stepNumber={1}>
    Create a new .NET MAUI or .NET Android/iOS project for this quickstart.

    <Tabs>
      <Tab title=".NET MAUI">
        **In Visual Studio 2022 or later:**

        1. **File** → **New** → **Project**
        2. Select **.NET MAUI App** template
        3. Configure your project:
           * **Project name**: `Auth0MauiSample`
           * **Location**: Choose your preferred location
           * **Framework**: **.NET 8.0 or later**
        4. Click **Create**
      </Tab>

      <Tab title=".NET Android">
        **In Visual Studio 2022 or later:**

        1. **File** → **New** → **Project**
        2. Select **Android App (.NET)** template
        3. Configure your project:
           * **Project name**: `Auth0AndroidSample`
           * **Framework**: **.NET 8.0 or later**
        4. Click **Create**
      </Tab>

      <Tab title=".NET iOS">
        **In Visual Studio 2022 (Mac) or Visual Studio for Mac:**

        1. **File** → **New** → **Project**
        2. Select **iOS App (.NET)** template
        3. Configure your project:
           * **Project name**: `Auth0iOSSample`
           * **Framework**: **.NET 8.0 or later**
        4. Click **Create**
      </Tab>
    </Tabs>

    <Info>
      This quickstart focuses on .NET Android and iOS, which are the next generation of Xamarin.Android and Xamarin.iOS. If you're still using Xamarin, you can follow this guide as the integration is identical and the SDKs are compatible.
    </Info>
  </Step>

  <Step title="Install Auth0 SDK" stepNumber={2}>
    Add the Auth0 OIDC Client SDK to your project.

    <Tabs>
      <Tab title="Package Manager Console">
        Open the Package Manager Console (**View** → **Other Windows** → **Package Manager Console**) and install the appropriate package:

        **For .NET Android:**

        ```bash Package Manager Console theme={null}
        Install-Package Auth0.OidcClient.AndroidX
        ```

        **For .NET iOS:**

        ```bash Package Manager Console theme={null}
        Install-Package Auth0.OidcClient.iOS
        ```

        **For .NET MAUI (both platforms):**

        ```bash Package Manager Console theme={null}
        Install-Package Auth0.OidcClient.MAUI
        ```
      </Tab>

      <Tab title="Visual Studio for Mac">
        1. In the **Solution Pad**, Ctrl+click (or right-click) on the **Packages** folder
        2. Select **Add Packages...**
        3. Search for:
           * `Auth0.OidcClient.AndroidX` for Android
           * `Auth0.OidcClient.iOS` for iOS
           * `Auth0.OidcClient.MAUI` for MAUI projects
        4. Select the package and click **Add Package**
      </Tab>

      <Tab title=".NET CLI">
        Run the following command in your project directory:

        **For .NET Android:**

        ```bash Terminal theme={null}
        dotnet add package Auth0.OidcClient.AndroidX
        ```

        **For .NET iOS:**

        ```bash Terminal theme={null}
        dotnet add package Auth0.OidcClient.iOS
        ```

        **For .NET MAUI:**

        ```bash Terminal theme={null}
        dotnet add package Auth0.OidcClient.MAUI
        ```
      </Tab>
    </Tabs>

    <Tip>
      The Auth0 OIDC Client SDK handles all the OAuth 2.0 and OIDC protocol details, providing a simple API for authentication.
    </Tip>
  </Step>

  <Step title="Setup your Auth0 App" stepNumber={3}>
    Create a new application in your Auth0 tenant and configure it for mobile.

    1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
    2. Click on **Applications** → **Applications** → **Create Application**
    3. Enter a name for your app, select **Native** as the app type, and click **Create**
    4. Switch to the **Settings** tab on the Application Details page
    5. Note your **Domain** and **Client ID** - you'll need these in the next step

    **Configure Callback URLs:**

    On the **Settings** tab, add the following URLs:

    **Allowed Callback URLs:**

    <Tabs>
      <Tab title="Android">
        ```
        YOUR_ANDROID_PACKAGE_NAME://{yourDomain}/android/YOUR_ANDROID_PACKAGE_NAME/callback
        ```

        Replace:

        * `YOUR_ANDROID_PACKAGE_NAME` with your app's package name (e.g., `com.mycompany.myapp`)
        * `{yourDomain}` with your Auth0 domain (e.g., `dev-abc123.us.auth0.com`)

        Example: `com.mycompany.myapp://dev-abc123.us.auth0.com/android/com.mycompany.myapp/callback`
      </Tab>

      <Tab title="iOS">
        ```
        YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback
        ```

        Replace:

        * `YOUR_BUNDLE_IDENTIFIER` with your app's bundle identifier (e.g., `com.mycompany.myapp`)
        * `{yourDomain}` with your Auth0 domain (e.g., `dev-abc123.us.auth0.com`)

        Example: `com.mycompany.myapp://dev-abc123.us.auth0.com/ios/com.mycompany.myapp/callback`
      </Tab>
    </Tabs>

    **Allowed Logout URLs:**

    Use the same URLs as your callback URLs.

    <Warning>
      Ensure that callback and logout URLs are in **lowercase**. Mismatched URLs will cause authentication to fail.
    </Warning>

    <Info>
      **Allowed Callback URLs** are essential for security - they ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail.

      **Allowed Logout URLs** provide a seamless experience when users sign out, redirecting them back to your app instead of leaving them on an Auth0 page.
    </Info>
  </Step>

  <Step title="Initialize the Auth0 Client" stepNumber={4}>
    Create an `Auth0Client` instance to communicate with Auth0.

    <Tabs>
      <Tab title="Android - MainActivity">
        ```cs MainActivity.cs lines theme={null}
        using Auth0.OidcClient;
        using Android.App;
        using Android.Content;

        [Activity(Label = "Auth0Sample", MainLauncher = true, Icon = "@drawable/icon",
            LaunchMode = LaunchMode.SingleTask)]
        [IntentFilter(
            new[] { Intent.ActionView },
            Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
            DataScheme = "YOUR_ANDROID_PACKAGE_NAME",
            DataHost = "{yourDomain}",
            DataPathPrefix = "/android/YOUR_ANDROID_PACKAGE_NAME/callback")]
        public class MainActivity : Activity
        {
            private Auth0Client auth0Client;

            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);

                // Initialize Auth0 client
                auth0Client = new Auth0Client(new Auth0ClientOptions
                {
                    Domain = "{yourDomain}",
                    ClientId = "{yourClientId}"
                }, this);
            }

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

        <Warning>
          Replace `YOUR_ANDROID_PACKAGE_NAME`, `{yourDomain}`, and `{yourClientId}` with your actual values. Ensure all text in `DataScheme`, `DataHost`, and `DataPathPrefix` is **lowercase**.
        </Warning>

        <Info>
          The `IntentFilter` registers your app to handle the callback URL. The `LaunchMode.SingleTask` ensures Android doesn't create a new activity instance when the callback is invoked.
        </Info>
      </Tab>

      <Tab title="iOS - AppDelegate">
        First, register the URL scheme in your `Info.plist`:

        ```xml Info.plist lines theme={null}
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeRole</key>
                <string>None</string>
                <key>CFBundleURLName</key>
                <string>Auth0</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>YOUR_BUNDLE_IDENTIFIER</string>
                </array>
            </dict>
        </array>
        ```

        Then, set up your `AppDelegate.cs`:

        ```cs AppDelegate.cs lines theme={null}
        using Auth0.OidcClient;
        using Foundation;
        using UIKit;

        [Register("AppDelegate")]
        public class AppDelegate : UIApplicationDelegate
        {
            private Auth0Client auth0Client;

            public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
            {
                // Initialize Auth0 client
                auth0Client = new Auth0Client(new Auth0ClientOptions
                {
                    Domain = "{yourDomain}",
                    ClientId = "{yourClientId}"
                });

                return true;
            }

            public override bool OpenUrl(UIApplication application, NSUrl url,
                string sourceApplication, NSObject annotation)
            {
                ActivityMediator.Instance.Send(url.AbsoluteString);
                return true;
            }
        }
        ```

        <Warning>
          Replace `YOUR_BUNDLE_IDENTIFIER`, `{yourDomain}`, and `{yourClientId}` with your actual values.
        </Warning>
      </Tab>
    </Tabs>

    <Tip>
      Store your Auth0 domain and client ID in a configuration file or app settings instead of hardcoding them for better maintainability.
    </Tip>
  </Step>

  <Step title="Implement Login and Logout" stepNumber={5}>
    Add methods to handle user authentication.

    **Implement Login:**

    ```cs Authentication.cs lines theme={null}
    public async Task LoginAsync()
    {
        var loginResult = await auth0Client.LoginAsync();

        if (!loginResult.IsError)
        {
            // Authentication successful
            var accessToken = loginResult.AccessToken;
            var idToken = loginResult.IdentityToken;
            var user = loginResult.User;

            // Store credentials and update UI
            Console.WriteLine($"Logged in as: {user.FindFirst("name")?.Value}");
        }
        else
        {
            // Handle authentication error
            Console.WriteLine($"Login error: {loginResult.Error}");
        }
    }
    ```

    **Implement Logout:**

    ```cs Authentication.cs lines theme={null}
    public async Task LogoutAsync()
    {
        var logoutResult = await auth0Client.LogoutAsync();

        if (logoutResult == BrowserResultType.Success)
        {
            // Clear stored credentials
            // Update UI to logged-out state
            Console.WriteLine("Logged out successfully");
        }
    }
    ```

    <Info>
      The `LoginAsync()` method launches the system browser (or Chrome Custom Tabs on Android) to display Auth0's Universal Login page. After authentication, the user is redirected back to your app via the callback URL.
    </Info>

    <Tip>
      Add these methods to your MainActivity (Android) or a ViewController (iOS) and call them when users tap Login/Logout buttons.
    </Tip>
  </Step>

  <Step title="Run your app" stepNumber={6}>
    Build and run your application.

    <Tabs>
      <Tab title="Visual Studio (Windows)">
        **For Android:**

        1. Select an Android emulator or connected device from the device dropdown
        2. Press **F5** or click the **Run** button
        3. The app will build, deploy, and launch

        **For iOS (requires Mac build host):**

        1. Connect to your Mac build host
        2. Select an iOS simulator or device from the device dropdown
        3. Press **F5** or click the **Run** button
      </Tab>

      <Tab title="Visual Studio for Mac">
        1. Select your target platform (Android/iOS) from the device dropdown
        2. Select an emulator/simulator or connected device
        3. Press **⌘+Return** or click the **Run** button
        4. The app will build and launch
      </Tab>

      <Tab title=".NET CLI">
        **For Android:**

        ```bash Terminal theme={null}
        dotnet build -f net8.0-android
        dotnet run -f net8.0-android
        ```

        **For iOS:**

        ```bash Terminal theme={null}
        dotnet build -f net8.0-ios
        dotnet run -f net8.0-ios
        ```
      </Tab>
    </Tabs>

    **Expected flow:**

    1. App launches with Login button
    2. Tap **Log In** → Browser/Chrome Custom Tab opens → Complete authentication
    3. Redirects back to your app automatically
    4. User is authenticated successfully

    <Tip>
      On first run, iOS may prompt you to confirm opening the browser for authentication. This is normal and expected behavior.
    </Tip>
  </Step>
</Steps>

<Check>
  **Checkpoint**

  You now have a fully functional Auth0 login experience in your .NET Android or iOS application. The app uses the system browser for secure authentication and automatically handles the callback flow.
</Check>

***

## Access User Information

After successful authentication, you can access user information from the login result.

### Authentication Result

The `LoginAsync()` method returns a `LoginResult` object containing:

```cs UserInfo.cs lines theme={null}
var loginResult = await auth0Client.LoginAsync();

if (!loginResult.IsError)
{
    // Access tokens
    var accessToken = loginResult.AccessToken;
    var idToken = loginResult.IdentityToken;
    var refreshToken = loginResult.RefreshToken;

    // Access user claims
    var user = loginResult.User;
    var name = user.FindFirst("name")?.Value;
    var email = user.FindFirst("email")?.Value;
    var picture = user.FindFirst("picture")?.Value;

    Console.WriteLine($"Name: {name}");
    Console.WriteLine($"Email: {email}");
}
```

### Iterate Through All Claims

To see all available user information:

```cs UserClaims.cs lines theme={null}
if (!loginResult.IsError)
{
    foreach (var claim in loginResult.User.Claims)
    {
        Console.WriteLine($"{claim.Type}: {claim.Value}");
    }
}
```

<Info>
  The exact claims returned depend on the scopes requested. For more information, see [Using Scopes](https://auth0.github.io/auth0-oidc-client-net/documentation/advanced-scenarios/scopes.html) in the Auth0 OIDC Client documentation.
</Info>

### Request Custom Scopes

To request additional user information, specify scopes when creating the Auth0Client:

```cs CustomScopes.cs lines theme={null}
var auth0Client = new Auth0Client(new Auth0ClientOptions
{
    Domain = "{yourDomain}",
    ClientId = "{yourClientId}",
    Scope = "openid profile email offline_access read:posts"
});
```

***

## Troubleshooting & Advanced

<Accordion title="Common Issues & Solutions">
  ### Browser doesn't redirect back to app

  **Solutions:**

  1. Verify callback URLs in Auth0 Dashboard exactly match your app's package name/bundle identifier
  2. Ensure callback URLs are in **lowercase**
  3. Check that `DataScheme`, `DataHost`, and `DataPathPrefix` (Android) or URL scheme (iOS) match your configuration
  4. Clean and rebuild your project

  ### Authentication fails with "Invalid Callback URL" error

  **Fix:**

  * Double-check that your callback URL in the Auth0 Dashboard matches the format:
    * Android: `packagename://yourdomain/android/packagename/callback`
    * iOS: `bundleidentifier://yourdomain/ios/bundleidentifier/callback`
  * Ensure the URL is in lowercase
  * Verify the Domain in your code matches the Domain in the Auth0 Dashboard

  ### LoginAsync() hangs or never completes

  **Solutions:**

  * Ensure the Intent filter (Android) or URL scheme (iOS) is properly configured
  * Check that `OnNewIntent()` (Android) or `OpenUrl()` (iOS) calls the `ActivityMediator`
  * Verify your app can open the system browser
  * Check network connectivity

  ### Error: "Default App must use Token Endpoint Authentication Method 'None'"

  **Fix:**

  1. Go to your Auth0 Application Settings in the Dashboard
  2. Scroll to **Application Properties**
  3. Set **Application Type** to **Native**
  4. Set **Token Endpoint Authentication Method** to **None**
  5. Click **Save Changes**

  ### iOS: Browser doesn't open

  **Solutions:**

  * Verify `Info.plist` contains the correct URL scheme configuration
  * Check that `OpenUrl()` is implemented in `AppDelegate`
  * Ensure iOS deployment target is compatible with your Auth0 SDK version
</Accordion>

<Accordion title="Production Considerations">
  ### Security Best Practices

  * **Secure Token Storage**: Use platform-specific secure storage (Android Keystore, iOS Keychain) to store tokens
  * **Token Refresh**: Implement refresh token handling to maintain user sessions
  * **Certificate Pinning**: Consider certificate pinning for additional API security
  * **ProGuard/Code Obfuscation**: Add appropriate rules if using code obfuscation on Android

  ### App Store Requirements

  * **Privacy Policy**: Ensure your app has a privacy policy that describes Auth0 usage
  * **User Data Handling**: Follow platform guidelines for handling user authentication data
  * **Deep Linking**: Test callback URL handling thoroughly across different scenarios
  * **Network Requirements**: Handle offline scenarios gracefully

  ### Performance Optimization

  * **Cache Auth0Client**: Create a single instance and reuse it throughout your app
  * **Lazy Loading**: Initialize Auth0Client only when needed
  * **Background Refresh**: Implement background token refresh for long-running sessions
</Accordion>

<Accordion title="Advanced Configuration">
  ### Custom Scopes and Audience

  Request specific scopes and set an audience for your API:

  ```cs AdvancedAuth.cs expandable lines theme={null}
  var auth0Client = new Auth0Client(new Auth0ClientOptions
  {
      Domain = "{yourDomain}",
      ClientId = "{yourClientId}",
      Scope = "openid profile email offline_access read:posts write:posts",
      Audience = "https://myapi.example.com"
  });

  var loginResult = await auth0Client.LoginAsync();
  ```

  ### Additional Parameters

  Pass additional parameters to the authorization request:

  ```cs ExtraParams.cs expandable lines theme={null}
  var extraParameters = new Dictionary<string, string>
  {
      { "prompt", "login" },
      { "ui_locales", "es" },
      { "custom_param", "value" }
  };

  var loginResult = await auth0Client.LoginAsync(extraParameters);
  ```

  ### Refresh Tokens

  Use refresh tokens to get new access tokens without user interaction:

  ```cs RefreshToken.cs expandable lines theme={null}
  var refreshResult = await auth0Client.RefreshTokenAsync(loginResult.RefreshToken);

  if (!refreshResult.IsError)
  {
      var newAccessToken = refreshResult.AccessToken;
      var newIdToken = refreshResult.IdentityToken;
      // Store new tokens
  }
  ```

  <Info>
    To receive a refresh token, include the `offline_access` scope in your authentication request.
  </Info>

  ### Platform-Specific Browser Configuration

  **Android - Use Chrome Custom Tabs with custom colors:**

  ```cs AndroidBrowser.cs expandable lines theme={null}
  var auth0Client = new Auth0Client(new Auth0ClientOptions
  {
      Domain = "{yourDomain}",
      ClientId = "{yourClientId}",
      Browser = new AndroidBrowser
      {
          ToolbarColor = Android.Graphics.Color.ParseColor("#FF6B35")
      }
  }, this);
  ```

  **iOS - Use SFSafariViewController with custom presentation:**

  ```cs iOSBrowser.cs expandable lines theme={null}
  var auth0Client = new Auth0Client(new Auth0ClientOptions
  {
      Domain = "{yourDomain}",
      ClientId = "{yourClientId}",
      Browser = new ASWebAuthenticationSessionBrowser
      {
          PrefersEphemeralWebBrowserSession = false
      }
  });
  ```
</Accordion>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Configure Identity Providers" icon="key" href="/docs/authenticate/identity-providers" iconType="solid">
    Add social login providers like Google, Facebook, and GitHub
  </Card>

  <Card title="Enable Multi-Factor Authentication" icon="shield-halved" href="/docs/secure/multi-factor-authentication" iconType="solid">
    Add an extra layer of security with MFA
  </Card>

  <Card title="Attack Protection" icon="shield" href="/docs/secure/attack-protection" iconType="solid">
    Learn how to protect against brute force and bot attacks
  </Card>

  <Card title="Customize Login Experience" icon="paintbrush" href="/docs/customize/universal-login-pages" iconType="solid">
    Customize the Universal Login page to match your brand
  </Card>
</CardGroup>
