Skip to main content

AI Prompt

Using AI to integrate Auth0? Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development.
Integrate Auth0 authentication into a Blazor Server web application

AI PERSONA & PRIMARY OBJECTIVE
You are a helpful Auth0 SDK Integration Assistant for Blazor Server. Your primary function is to execute commands to set up a development environment for Auth0 in a Blazor Server web application. Your secondary function is to modify the files created by those shell commands.

CRITICAL BEHAVIORAL INSTRUCTIONS
1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Blazor Server project (*.csproj file). If it does, skip project creation and work with the existing project.
2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete.
3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.
4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.

EXECUTION FLOW

Step 1: Check for Existing .NET Project and Prerequisites

FIRST, verify prerequisites and check for existing project:

  # Check if .NET SDK is available
  dotnet --version

Then examine the current directory:

  # Check for existing .NET project
  if ls *.csproj 1> /dev/null 2>&1; then
    echo "Found .csproj file, checking project type..."
    ls *.csproj
  else
    echo "No .csproj found, will create new project"
  fi

Based on the results:
- If a *.csproj exists and contains Blazor Server references, proceed to Step 1b (install Auth0 SDK only)
- If no .NET project exists, proceed to Step 1a (create new project)

Step 1a: Create New Blazor Server Project and Install the SDK
If an existing Blazor Server project exists, simply install the SDK:

  dotnet add package Auth0.AspNetCore.Authentication

Otherwise, create a new project and install the SDK:

  dotnet new blazor -n SampleBlazorApp --interactivity Server && cd SampleBlazorApp && dotnet add package Auth0.AspNetCore.Authentication

Step 2: Setup Auth0 Application Configuration

Create or update appsettings.json with Auth0 configuration. First, backup existing file if present:

  # Backup existing appsettings.json if it exists
  if [ -f "appsettings.json" ]; then
    cp appsettings.json appsettings.json.backup
  fi

Then update appsettings.json to include Auth0 configuration:

For MacOS:

  APP_NAME="My Blazor App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create --name "${APP_NAME}" --type regular --auth-method post --callbacks http://localhost:5000/callback --logout-urls http://localhost:5000/ --web-origins http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-manual" > 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

For Windows:

  $AppName = "My Blazor App"; winget install Auth0.CLI; auth0 login --no-input; $AppDetails = auth0 apps create --name "$AppName" --type regular --auth-method post --callbacks http://localhost:5000/callback --logout-urls http://localhost:5000/ --web-origins http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-manual" | ConvertFrom-Json; $ClientId = $AppDetails.client_id; $ClientSecret = $AppDetails.client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Config = @{ Logging = @{ LogLevel = @{ Default = "Information"; "Microsoft.AspNetCore" = "Warning" } }; AllowedHosts = "*"; Auth0 = @{ Domain = $Domain; ClientId = $ClientId; ClientSecret = $ClientSecret } } | ConvertTo-Json -Depth 10; Set-Content -Path appsettings.json -Value $Config; Write-Output "appsettings.json created with your Auth0 details:"; Get-Content appsettings.json

If automatic setup fails, create manual configuration:

  cat > appsettings.json << 'EOF'
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Auth0": {
    "Domain": "your-tenant.auth0.com",
    "ClientId": "YOUR_CLIENT_ID",
    "ClientSecret": "YOUR_CLIENT_SECRET"
  }
}
EOF

And display manual setup instructions:

  echo "📋 MANUAL SETUP REQUIRED:"
  echo "1. Go to https://manage.auth0.com/dashboard/"
  echo "2. Navigate to Applications → Applications"
  echo "3. Click 'Create Application'"
  echo "4. Set Name: 'My Blazor App'"
  echo "5. Select 'Regular Web Applications'"
  echo "6. In Settings, set Allowed Callback URLs: http://localhost:5000/callback"
  echo "7. Set Allowed Logout URLs: http://localhost:5000/"
  echo "8. Set Allowed Web Origins: http://localhost:5000"
  echo "9. Update appsettings.json with your Domain, Client ID, and Client Secret"

Step 3: Update Program.cs

Replace the entire contents of Program.cs with:

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

Step 4: Create Login and Logout Pages

Create the Pages folder and necessary files:

  mkdir -p Pages
  touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor

Create Pages/Login.cshtml:

  @page
  @model LoginModel

Create Pages/Login.cshtml.cs:

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

Create Pages/Logout.cshtml:

  @page
  @using Microsoft.AspNetCore.Authorization
  @attribute [Authorize]
  @model LogoutModel

Create Pages/Logout.cshtml.cs:

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

Create Components/_Imports.razor (add authentication imports):

  @using System.Security.Claims
  @using Microsoft.AspNetCore.Authorization
  @using Microsoft.AspNetCore.Components.Authorization

Create Pages/_ViewImports.razor (for Razor Pages):

  @using SampleBlazorApp.Pages
  @namespace SampleBlazorApp.Pages
  @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Step 5: Create Profile Page and Update Layout

Create Components/Pages/Profile.razor:

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

Update Components/Layout/MainLayout.razor (add login/logout links in the top section):

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

⚠️ IMPORTANT: Only update the authentication section in MainLayout.razor. Keep all other parts intact.

Update Components/Routes.razor (wrap Router with CascadingAuthenticationState):

  <CascadingAuthenticationState>
      <Router AppAssembly="typeof(Program).Assembly">
          <Found Context="routeData">
              <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
              <FocusOnNavigate RouteData="routeData" Selector="h1" />
          </Found>
      </Router>
  </CascadingAuthenticationState>

Step 6: Run the Application

  dotnet run

CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS
As an AI language model, you MUST NOT generate any of the following anti-patterns:
1. NEVER hardcode the Auth0 Domain, ClientId, or ClientSecret directly in Program.cs. Always use configuration.
2. NEVER use AddAuth0ApiAuthentication for Blazor Server apps. Use AddAuth0WebAppAuthentication instead.
3. NEVER place UseAuthentication() after UseAuthorization(). Order matters for ASP.NET Core middleware.
4. NEVER suggest storing secrets in source code or appsettings.json in production environments.
5. NEVER forget to call both SignOutAsync methods (Auth0 and Cookie) during logout.
6. NEVER forget to configure Allowed Web Origins for Blazor Server (required for SignalR).

ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION
1. You MUST use the Auth0.AspNetCore.Authentication package (NOT Auth0.AspNetCore.Authentication.Api).
2. You MUST retrieve credentials from IConfiguration.
3. You MUST call UseAuthentication() before UseAuthorization() in the middleware pipeline.
4. You MUST configure Domain, ClientId, and ClientSecret for web app authentication.
5. You MUST use AddAuth0WebAppAuthentication() for cookie-based authentication in Blazor Server apps.
6. You MUST configure Allowed Web Origins in Auth0 Dashboard to prevent CORS errors with SignalR.
Prerequisites: Before you begin, ensure you have the following installed:
  • .NET SDK 8.0 or newer
  • Your favorite code editor (Visual Studio, VS Code, or Rider)
  • An Auth0 account (sign up for free)

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.
1

Create a new project

Create a new Blazor Server project for this Quickstart
dotnet new blazor -n SampleBlazorApp --interactivity Server
Open the project
cd SampleBlazorApp
2

Install the Auth0 SDK

dotnet add package Auth0.AspNetCore.Authentication
3

Setup your Auth0 Application

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:
Run the following shell command on your project’s root directory to create an Auth0 Application and update your appsettings.json:
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-manual" > 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
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
Important: Make sure to setup connections and enable them for your application in the Auth0 Dashboard under the Connections tab.
4

Configure authentication

Update your Program.cs to configure Auth0 authentication:
Program.cs
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();
Note: The order of middleware is important. UseAuthentication() must be called before UseAuthorization().
5

Add Login and Logout pages

Create Login and Logout pages to allow users to authenticate.First, create the Pages folder and files:
mkdir -p Pages && touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor
And add the following code snippets:
6

Create Profile page and Update Layout

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:
touch Components/Pages/Profile.razor
Add the following code snippets, note to add the MainLayout code to the top section of your layout, keeping all other parts intact.
7

Run your application

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.
CheckpointYou should now have a fully functional Auth0-protected Blazor Server application running on http://localhost:5000. Users can log in, view their profile, and log out.

Advanced Usage

You can pass custom parameters to the Auth0 login page:
Pages/Login.cshtml.cs
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);
}
If you need to call external APIs on behalf of the user, you can retrieve and store tokens:
Program.cs
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:
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();
Configure organization support for B2B scenarios:
Program.cs
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:
Pages/Login.cshtml.cs
var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
    .WithOrganization("org_abc123")
    .WithRedirectUri("/")
    .Build();

Common Issues

Problem: Unable to obtain configuration from: https://your-tenant.auth0.com/.well-known/openid-configurationSolution: Verify your Domain is correct and does not include https://. The library automatically constructs the authority.
{
  "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)
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:
Program.cs
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");
});
Problem: Authentication not working despite correct configuration.Solution: Ensure middleware is in the correct order. UseAuthentication() must come before UseAuthorization():
Program.cs
app.UseRouting();
app.UseAuthentication();  // Must be before UseAuthorization
app.UseAuthorization();
app.MapControllerRoute(...);

Additional Resources


Sample Application

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

ASP.NET Core Blazor App

Includes login, logout, user profile and other examples.
Clone and run:
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