> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-actions-triggers-prototype.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> This guide demonstrates how to integrate Auth0 with any new or existing Blazor Server application using the Auth0.AspNetCore.Authentication SDK.

# Add Login to Your Blazor Server Application

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

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

<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-aspnetcore-authentication
  ```

  **Then ask your AI assistant:**

  ```text theme={null}
  Add Auth0 authentication to my Blazor Server app
  ```

  Your AI assistant will automatically create your Auth0 application, fetch credentials, install the Auth0 ASP.NET Core Authentication SDK, configure authentication middleware, and implement login/logout flows. [Full agent skills documentation →](/docs/quickstart/agent-skills)
</Accordion>

<Note>
  **Prerequisites:** Before you begin, ensure you have the following installed:

  * **[.NET SDK](https://dotnet.microsoft.com/download)** 8.0 or newer
  * Your favorite code editor (Visual Studio, VS Code, or Rider)
  * An Auth0 account ([sign up for free](https://auth0.com/signup))
</Note>

## Get Started

Auth0 allows you to quickly add authentication and gain access to user profile information in your application. This guide demonstrates how to integrate Auth0 with any new or existing Blazor Server application using the `Auth0.AspNetCore.Authentication` SDK.

<Steps>
  <Step title="Create a new project" stepNumber={1}>
    Create a new Blazor Server project for this Quickstart

    ```shellscript theme={null}
    dotnet new blazor -n SampleBlazorApp --interactivity Server
    ```

    Open the project

    ```shellscript theme={null}
    cd SampleBlazorApp
    ```
  </Step>

  <Step title="Install the Auth0 SDK" stepNumber={2}>
    ```shellscript theme={null}
    dotnet add package Auth0.AspNetCore.Authentication
    ```
  </Step>

  <Step title="Setup your Auth0 Application" stepNumber={3}>
    Next up, you need to create a new Application on your Auth0 tenant and add the configuration to your project.

    You can choose to do this automatically by running a CLI command or do it manually via the Dashboard:

    <Tabs>
      <Tab title="CLI">
        Run the following shell command on your project's root directory to create an Auth0 Application and update your `appsettings.json`:

        <Tabs>
          <Tab title="Mac/Linux">
            ```shellscript theme={null}
            AUTH0_APP_NAME="My Blazor App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && rm auth0-app-details.json && cat > appsettings.json << EOF
            {
              "Logging": {
                "LogLevel": {
                  "Default": "Information",
                  "Microsoft.AspNetCore": "Warning"
                }
              },
              "AllowedHosts": "*",
              "Auth0": {
                "Domain": "${DOMAIN}",
                "ClientId": "${CLIENT_ID}",
                "ClientSecret": "${CLIENT_SECRET}"
              }
            }
            EOF
            echo "appsettings.json created with your Auth0 details:" && cat appsettings.json
            ```
          </Tab>

          <Tab title="Windows (PowerShell)">
            ```powershell theme={null}
            $AUTH0_APP_NAME = "My Blazor App"
            $latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/auth0/auth0-cli/releases/latest"
            $latestVersion = $latestRelease.tag_name
            $version = $latestVersion -replace "^v"
            Invoke-WebRequest -Uri "https://github.com/auth0/auth0-cli/releases/download/${latestVersion}/auth0-cli_${version}_Windows_x86_64.zip" -OutFile ".\auth0.zip"
            Expand-Archive ".\auth0.zip" .\
            [System.Environment]::SetEnvironmentVariable('PATH', $Env:PATH + ";${pwd}")
            auth0 login --no-input
            auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" | Set-Content -Path auth0-app-details.json
            $AppDetails = Get-Content -Raw auth0-app-details.json | ConvertFrom-Json
            $ClientId = $AppDetails.client_id
            $ClientSecret = $AppDetails.client_secret
            $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name
            $Config = Get-Content -Raw appsettings.json | ConvertFrom-Json
            if (-not $Config.Auth0) { $Config | Add-Member -MemberType NoteProperty -Name Auth0 -Value @{} }
            $Config.Auth0.Domain = $Domain
            $Config.Auth0.ClientId = $ClientId
            $Config.Auth0.ClientSecret = $ClientSecret
            $Config | ConvertTo-Json -Depth 10 | Set-Content appsettings.json
            Remove-Item auth0-app-details.json
            Write-Output "✅ appsettings.json updated with your Auth0 details:"
            Get-Content appsettings.json
            ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab title="Dashboard">
        Before you start, create or update `appsettings.json` on your project's root directory

        ```json appsettings.json theme={null}
        {
          "Logging": {
            "LogLevel": {
              "Default": "Information",
              "Microsoft.AspNetCore": "Warning"
            }
          },
          "AllowedHosts": "*",
          "Auth0": {
            "Domain": "YOUR_AUTH0_DOMAIN",
            "ClientId": "YOUR_CLIENT_ID",
            "ClientSecret": "YOUR_CLIENT_SECRET"
          }
        }
        ```

        1. Go to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
        2. Click **Applications → Applications → Create Application**
        3. Enter a name for your application (e.g., "My Blazor App")
        4. Select **Regular Web Application** as the application type
        5. Click **Create**
        6. Go to the **Settings** tab
        7. Replace `YOUR_AUTH0_DOMAIN`, `YOUR_CLIENT_ID`, and `YOUR_CLIENT_SECRET` in the `appsettings.json` file with the **Domain**, **Client ID**, and **Client Secret** values from the dashboard
      </Tab>
    </Tabs>

    **Configure Callback URLs:**

    In the **Settings** tab, configure the following URLs:

    * **Allowed Callback URLs**: `http://localhost:5000/callback`
    * **Allowed Logout URLs**: `http://localhost:5000`
    * **Allowed Web Origins**: `http://localhost:5000`

    Click **Save Changes**

    <Info>
      **Important:** Make sure to [setup connections](https://auth0.com/docs/get-started/applications/set-up-database-connections) and enable them for your application in the Auth0 Dashboard under the **Connections** tab.
    </Info>
  </Step>

  <Step title="Configure authentication" stepNumber={4}>
    Update your `Program.cs` to configure Auth0 authentication:

    ```csharp Program.cs lines theme={null}
    using Auth0.AspNetCore.Authentication;
    using SampleBlazorApp.Components;

    var builder = WebApplication.CreateBuilder(args);

    // Add Auth0 authentication
    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"];
        options.ClientId = builder.Configuration["Auth0:ClientId"];
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
    });

    // Add Razor Components and Blazor Server
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();

    // Add cascading authentication state
    builder.Services.AddCascadingAuthenticationState();

    // Add Razor Pages for authentication endpoints
    builder.Services.AddRazorPages();

    var app = builder.Build();

    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseAntiforgery();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapStaticAssets();
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();

    // Map Razor Pages for authentication
    app.MapRazorPages();

    app.Run();
    ```

    <Info>
      **Note:** The order of middleware is important. `UseAuthentication()` must be called before `UseAuthorization()`.
    </Info>
  </Step>

  <Step title="Add Login and Logout pages" stepNumber={5}>
    Create Login and Logout pages to allow users to authenticate.

    First, create the `Pages` folder and files:

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        mkdir -p Pages && touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType Directory -Force -Path Pages; New-Item -ItemType File -Force -Path Pages/Login.cshtml, Pages/Login.cshtml.cs, Pages/Logout.cshtml, Pages/Logout.cshtml.cs, Pages/_ViewImports.razor
        ```
      </Tab>
    </Tabs>

    And add the following code snippets:

    <AuthCodeGroup>
      ```razor Pages/Login.cshtml lines theme={null}
      @page
      @model LoginModel
      ```

      ```csharp Pages/Login.cshtml.cs lines theme={null}
      using Auth0.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Mvc.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          public class LoginModel : PageModel
          {
              public async Task OnGet(string redirectUri = "/")
              {
                  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                      .WithRedirectUri(redirectUri)
                      .Build();

                  await HttpContext.ChallengeAsync(
                      Auth0Constants.AuthenticationScheme,
                      authenticationProperties);
              }
          }
      }
      ```

      ```razor Pages/Logout.cshtml lines theme={null}
      @page
      @using Microsoft.AspNetCore.Authorization
      @attribute [Authorize]
      @model LogoutModel
      ```

      ```csharp Pages/Logout.cshtml.cs lines theme={null}
      using Auth0.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication.Cookies;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          [Authorize]
          public class LogoutModel : PageModel
          {
              public async Task OnGet()
              {
                  var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                      .WithRedirectUri("/")
                      .Build();

                  await HttpContext.SignOutAsync(
                      Auth0Constants.AuthenticationScheme,
                      authenticationProperties);
                      
                  await HttpContext.SignOutAsync(
                      CookieAuthenticationDefaults.AuthenticationScheme);
              }
          }
      }
      ```

      ```razor Components/_Imports.razor lines theme={null}
      @using System.Security.Claims
      @using Microsoft.AspNetCore.Authorization
      @using Microsoft.AspNetCore.Components.Authorization
      ```

      ```razor Pages/_ViewImports.razor lines theme={null}
      @using SampleBlazorApp.Pages
      @namespace SampleBlazorApp.Pages
      @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Create Profile page and Update Layout" stepNumber={6}>
    Create a custom user profile page for displaying the user's name and claims, and update the layout to add login/logout links.

    First, create the Profile component:

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        touch Components/Pages/Profile.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType File -Force -Path Components/Pages/Profile.razor
        ```
      </Tab>
    </Tabs>

    Add the following code snippets, note to add the `MainLayout` code to the top section of your layout, keeping all other parts intact.

    <AuthCodeGroup>
      ```razor Components/Pages/Profile.razor expandable lines theme={null}
      @page "/profile"
      @attribute [Authorize]

      <PageTitle>User Profile</PageTitle>

      <AuthorizeView>
          <Authorized>
              <div class="profile-container">
                  <img src="@context.User.FindFirst("picture")?.Value" 
                       alt="Profile picture" 
                       class="profile-picture" />
                  
                  <h3>Welcome, @context.User.Identity?.Name!</h3>
                  
                  <div class="profile-details">
                      <p><strong>Email:</strong> @context.User.FindFirst("email")?.Value</p>
                      <p><strong>Email Verified:</strong> @context.User.FindFirst("email_verified")?.Value</p>
                      <p><strong>Auth0 User ID:</strong> @context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value</p>
                  </div>

                  <h4>All Claims:</h4>
                  <table class="table">
                      <thead>
                          <tr>
                              <th>Claim Type</th>
                              <th>Claim Value</th>
                          </tr>
                      </thead>
                      <tbody>
                          @foreach (var claim in context.User.Claims)
                          {
                              <tr>
                                  <td>@claim.Type</td>
                                  <td>@claim.Value</td>
                              </tr>
                          }
                      </tbody>
                  </table>
              </div>
          </Authorized>
          <NotAuthorized>
              <p>You must be logged in to view this page.</p>
              <a href="/Login?redirectUri=/profile">Log in</a>
          </NotAuthorized>
      </AuthorizeView>
      ```

      ```razor Components/Layout/MainLayout.razor lines theme={null}
      <div class="top-row px-4">
          <AuthorizeView>
              <NotAuthorized>
                  <a href="/Login">Log in</a>
              </NotAuthorized>
              <Authorized>
                  <span>Hello, @context.User.Identity?.Name!</span>
                  <a href="/Profile">Profile</a>
                  <a href="/Logout">Log out</a>
              </Authorized>
          </AuthorizeView>
      </div>
      ```

      ```razor Components/Routes.razor lines theme={null}
      <CascadingAuthenticationState>
          <Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
              <Found Context="routeData">
                  <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
                  <FocusOnNavigate RouteData="routeData" Selector="h1" />
              </Found>
          </Router>
      </CascadingAuthenticationState>
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Run your application" stepNumber={7}>
    ```shellscript theme={null}
    dotnet run
    ```

    Your application should start and display the URL it's listening on:

    ```
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:5000
    ```

    Open your browser and navigate to `http://localhost:5000`. Click the **Login** link in the navigation. You'll be redirected to Auth0's login page.
    After logging in, you'll be redirected back to your application, and you should see your name in the navigation.
  </Step>
</Steps>

<Check>
  **Checkpoint**

  You should now have a fully functional Auth0-protected Blazor Server application running on [http://localhost:5000](http://localhost:5000). Users can log in, view their profile, and log out.
</Check>

***

## Advanced Usage

<Accordion title="Customize Login Parameters">
  You can pass custom parameters to the Auth0 login page:

  ```csharp Pages/Login.cshtml.cs theme={null}
  public async Task OnGet(string redirectUri = "/")
  {
      var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
          .WithRedirectUri(redirectUri)
          .WithParameter("screen_hint", "signup")  // Show signup page
          .WithParameter("ui_locales", "es")       // Set language to Spanish
          .Build();

      await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
  }
  ```
</Accordion>

<Accordion title="Store Tokens for API Calls">
  If you need to call external APIs on behalf of the user, you can retrieve and store tokens:

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
  })
  .WithAccessToken(options =>
  {
      options.Audience = "https://your-api.example.com";
      options.UseRefreshTokens = true;
  });
  ```

  Then retrieve the access token:

  ```csharp theme={null}
  var accessToken = await HttpContext.GetTokenAsync("access_token");

  // Use the access token to call your API
  var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization = 
      new AuthenticationHeaderValue("Bearer", accessToken);

  var response = await client.GetAsync("https://your-api.example.com/data");
  var data = await response.Content.ReadAsStringAsync();
  ```
</Accordion>

<Accordion title="Configure Organizations">
  Configure organization support for B2B scenarios:

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
      options.Organization = builder.Configuration["Auth0:Organization"];
  });
  ```

  Or specify organization at login time:

  ```csharp Pages/Login.cshtml.cs theme={null}
  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
      .WithOrganization("org_abc123")
      .WithRedirectUri("/")
      .Build();
  ```
</Accordion>

***

## Common Issues

<AccordionGroup>
  <Accordion title="Unable to obtain configuration">
    **Problem:** `Unable to obtain configuration from: https://your-tenant.auth0.com/.well-known/openid-configuration`

    **Solution:** Verify your Domain is correct and does not include `https://`. The library automatically constructs the authority.

    ```json theme={null}
    {
      "Auth0": {
        "Domain": "your-tenant.auth0.com"  // Correct - no protocol
      }
    }
    ```

    Also ensure:

    * No trailing slash in the domain value
    * Your application has internet access to reach Auth0
    * The domain format matches your tenant region (`.auth0.com`, `.us.auth0.com`, `.eu.auth0.com`)
  </Accordion>

  <Accordion title="Configuration values not found">
    **Problem:** `ArgumentNullException: Value cannot be null. (Parameter 'Domain')` or similar.

    **Solution:** Ensure `appsettings.json` contains the Auth0 section with Domain, ClientId, and ClientSecret values. Check that configuration is being read correctly:

    ```csharp Program.cs theme={null}
    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"]
            ?? throw new InvalidOperationException("Auth0:Domain is required");
        options.ClientId = builder.Configuration["Auth0:ClientId"]
            ?? throw new InvalidOperationException("Auth0:ClientId is required");
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"]
            ?? throw new InvalidOperationException("Auth0:ClientSecret is required");
    });
    ```
  </Accordion>

  <Accordion title="Middleware order issues">
    **Problem:** Authentication not working despite correct configuration.

    **Solution:** Ensure middleware is in the correct order. `UseAuthentication()` must come before `UseAuthorization()`:

    ```csharp Program.cs theme={null}
    app.UseRouting();
    app.UseAuthentication();  // Must be before UseAuthorization
    app.UseAuthorization();
    app.MapControllerRoute(...);
    ```
  </Accordion>
</AccordionGroup>

***

## Additional Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/auth0/auth0-aspnetcore-authentication">
    Source code and issue tracker
  </Card>

  <Card title="API Reference" icon="code" href="https://auth0.github.io/auth0-aspnetcore-authentication/">
    Detailed API documentation
  </Card>

  <Card title="Community Forum" icon="comments" href="https://community.auth0.com/">
    Get help from the Auth0 community
  </Card>
</CardGroup>

***

## Sample Application

A sample application can be found below that demonstrates the integration of Auth0 with ASP.NET Core MVC.:

<Card title="ASP.NET Core Blazor App" icon="github" href="https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample">
  Includes login, logout, user profile and other examples.
</Card>

Clone and run:

```bash theme={null}
git clone https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample

# Update appsettings.json with your Auth0 configuration
dotnet run
```

***
