Add Auth0 JWT authentication to an ASP.NET Core Web API with protected endpoints
This Quickstart is currently in Beta. We’d love to hear your feedback!
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.
Report incorrect code
Copy
Ask AI
Integrate the Auth0 ASP.NET Core API SDK into a .NET Web APIAI PERSONA & PRIMARY OBJECTIVEYou are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0 in ASP.NET Core. Your secondary function is to modify the files created by those commands.CRITICAL BEHAVIORAL INSTRUCTIONS1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a .NET 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 FLOWStep 1: Check for Existing .NET Project and PrerequisitesFIRST, verify prerequisites and check for existing .NET project: # Check if .NET SDK is available dotnet --versionThen 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 -la *.csproj else echo "No .csproj found, will create new project" fiBased on the results:- If *.csproj exists and is a Web API project, proceed to Step 1b (install Auth0 SDK only)- If no .NET project exists, proceed to Step 1a (create new project)Step 1a: Create New Project and Install the SDKIf an existing Web API project exists, simply install the SDK:dotnet add package Auth0.AspNetCore.Authentication.ApiOtherwise, create a new project and install the SDK: dotnet new webapi -n Auth0Api && cd Auth0Api && dotnet add package Auth0.AspNetCore.Authentication.ApiStep 2: Modify & Create FilesAFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory.2.1: Setup Auth0 configuration in appsettings.jsonAdd the Auth0 configuration section to appsettings.json: { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Auth0": { "Domain": "your-tenant.auth0.com", "Audience": "https://my-api" } }⚠️ IMPORTANT: Update the Domain and Audience values with your actual Auth0 API configuration.2.2: Configure Program.cs with Auth0 authenticationReplace the entire contents of Program.cs with this code: using Auth0.AspNetCore.Authentication.Api; using Microsoft.AspNetCore.Authentication.JwtBearer; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuth0ApiAuthentication(options => { options.Domain = builder.Configuration["Auth0:Domain"]; options.JwtBearerOptions = new JwtBearerOptions { Audience = builder.Configuration["Auth0:Audience"] }; }); builder.Services.AddAuthorization(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); } app.UseAuthentication(); app.UseAuthorization(); // Public endpoint - no authentication required app.MapGet("/api/public", () => Results.Ok(new { Message = "This endpoint is public" })) .WithName("GetPublic"); // Protected endpoint - requires authentication app.MapGet("/api/private", () => Results.Ok(new { Message = "This endpoint requires authentication" })) .RequireAuthorization() .WithName("GetPrivate"); app.Run();2.3: Run the application dotnet runThe API will start on https://localhost:7190 (or similar - check console output for exact URL).CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELSAs an AI language model, you MUST NOT generate any of the following anti-patterns:1. NEVER hardcode the Auth0 Domain or Audience directly in the code. This is a major security vulnerability.2. NEVER omit the UseAuthentication() middleware. It MUST be called before UseAuthorization().3. NEVER place authentication middleware after MapControllers() or endpoint mapping. Middleware order matters.4. NEVER suggest manually validating JWT tokens. The SDK handles this securely.ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION1. You MUST use the Auth0.AspNetCore.Authentication.Api package.2. You MUST retrieve credentials from configuration (appsettings.json).3. You MUST call UseAuthentication() before UseAuthorization() in the middleware pipeline.4. You MUST use RequireAuthorization() or [Authorize] attribute to protect endpoints.COMMON ISSUES ENCOUNTERED DURING INTEGRATIONIssue 1: Configuration values not foundProblem: Domain or Audience is null at runtimeSolution: Ensure appsettings.json contains the Auth0 section with correct valuesIssue 2: Middleware order issuesProblem: Authentication not working despite correct configurationSolution: Ensure UseAuthentication() comes before UseAuthorization() in Program.csIssue 3: 401 Unauthorized errorsProblem: Valid tokens are being rejectedSolution: Verify Domain doesn't include https:// and Audience exactly matches Auth0 API IdentifierIssue 4: HTTPS certificate errors in developmentProblem: SSL/TLS errors when running locallySolution: Run `dotnet dev-certs https --trust` to trust the development certificate
Prerequisites: Before you begin, ensure you have the following installed:
This quickstart demonstrates how to add Auth0 JWT authentication to an ASP.NET Core Web API. You’ll build a secure API with protected endpoints using the Auth0 ASP.NET Core API SDK.
1
Create a new project
Create a new ASP.NET Core Web API project for this Quickstart
Next up, you need to create a new API 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:
CLI
Dashboard
Run the following shell command on your project’s root directory to create an Auth0 API and update your appsettings.json file:
2. Create a controller:Create Controllers/MessagesController.cs:
Controllers/MessagesController.cs
Report incorrect code
Copy
Ask AI
using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;namespace Auth0Api.Controllers;[ApiController][Route("api/[controller]")]public class MessagesController : ControllerBase{ [HttpGet] public IActionResult GetPublic() { return Ok(new { Message = "This endpoint is public" }); } [Authorize] [HttpGet("private")] public IActionResult GetPrivate() { var userId = User.FindFirst("sub")?.Value; return Ok(new { Message = "This endpoint is protected", UserId = userId }); } [Authorize(Policy = "read:messages")] [HttpGet("messages")] public IActionResult GetMessages() { return Ok(new { Messages = new[] { "Message 1", "Message 2" } }); }}
Protecting Routes with Scope-Based Authorization
Protect endpoints based on specific scopes in the access token.1. Define scopes in your Auth0 API:In the Auth0 Dashboard → APIs → Your API → Permissions, add scopes:
Problem: Token validation fails with audience mismatch error.Solution: Ensure the Audience in appsettings.json exactly matches the Identifier of your Auth0 API. The audience claim in the token must match this value.
Report incorrect code
Copy
Ask AI
{ "Auth0": { "Audience": "https://my-api" // Must match Auth0 API Identifier }}
401 Unauthorized - Invalid issuer
Problem: Token validation fails with issuer error.Solution: Verify your Domain is correct and does not include https://. The library automatically constructs the authority as https://{Domain}.
Report incorrect code
Copy
Ask AI
{ "Auth0": { "Domain": "your-tenant.auth0.com" // No https:// }}
Configuration values not found
Problem:ArgumentNullException: Value cannot be null. (Parameter 'Domain') or similar.Solution: Ensure appsettings.json contains the Auth0 section with Domain and Audience values. Check that configuration is being read correctly:
Report incorrect code
Copy
Ask AI
builder.Services.AddAuth0ApiAuthentication(options =>{ options.Domain = builder.Configuration["Auth0:Domain"] ?? throw new InvalidOperationException("Auth0:Domain is required"); options.JwtBearerOptions = new JwtBearerOptions { Audience = builder.Configuration["Auth0:Audience"] ?? throw new InvalidOperationException("Auth0:Audience is required") };});
HTTPS certificate errors in development
Problem: SSL/TLS certificate errors when running locally.Solution: Trust the development certificate:
Problem: Authentication not working despite correct configuration.Solution: Ensure middleware is in the correct order. UseAuthentication() must come before UseAuthorization():
Report incorrect code
Copy
Ask AI
app.UseAuthentication(); // Must be before UseAuthorizationapp.UseAuthorization();app.MapControllers();
Scopes not working in authorization policies
Problem: Scope-based authorization policies always fail.Solution: Ensure your access token includes the required scopes. When requesting a token, specify the scopes:
Report incorrect code
Copy
Ask AI
curl --request POST \ --url https://YOUR_DOMAIN/oauth/token \ --data '{"client_id":"...","client_secret":"...","audience":"...","grant_type":"client_credentials","scope":"read:messages write:messages"}'
Also verify scopes are defined in your Auth0 API settings (Dashboard → APIs → Your API → Permissions).
git clone https://github.com/auth0/auth0-aspnetcore-api.gitcd auth0-aspnetcore-api/Auth0.AspNetCore.Authentication.Api.Playground# Update appsettings.json with your Auth0 configurationdotnet run