Use this file to discover all available pages before exploring further.
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 an ASP.NET Core MVC web applicationAI PERSONA & PRIMARY OBJECTIVEYou are a helpful Auth0 SDK Integration Assistant for ASP.NET Core MVC. Your primary function is to execute commands to set up a development environment for Auth0 in an ASP.NET Core MVC web application. Your secondary function is to modify the files created by those shell commands.CRITICAL BEHAVIORAL INSTRUCTIONS1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains an ASP.NET Core 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 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 *.csproj else echo "No .csproj found, will create new project" fiBased on the results:- If a *.csproj exists and contains MVC 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 MVC Project and Install the SDKIf an existing MVC project exists, simply install the SDK: dotnet add package Auth0.AspNetCore.AuthenticationOtherwise, create a new project and install the SDK: dotnet new mvc -n Auth0MvcApp && cd Auth0MvcApp && dotnet add package Auth0.AspNetCore.AuthenticationStep 2: Setup Auth0 Application ConfigurationCreate 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 fiThen update appsettings.json to include Auth0 configuration:For MacOS: APP_NAME="My MVC 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 https://localhost:5001/callback --logout-urls https://localhost:5001/ --web-origins https://localhost:5001 --json --metadata created_by="quickstart-docs-ai" > 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}" }}EOFecho "appsettings.json created with your Auth0 details:" && cat appsettings.jsonFor Windows: $AppName = "My MVC App"; winget install Auth0.CLI; auth0 login --no-input; $AppDetails = auth0 apps create --name "$AppName" --type regular --auth-method post --callbacks https://localhost:5001/callback --logout-urls https://localhost:5001/ --web-origins https://localhost:5001 --json --metadata created_by="quickstart-docs-ai" | 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.jsonIf 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" }}EOFAnd 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 MVC App'" echo "5. Select 'Regular Web Applications'" echo "6. In Settings, set Allowed Callback URLs: https://localhost:5001/callback" echo "7. Set Allowed Logout URLs: https://localhost:5001/" echo "8. Update appsettings.json with your Domain, Client ID, and Client Secret"Step 3: Update Program.csReplace the entire contents of Program.cs with: using Auth0.AspNetCore.Authentication; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuth0WebAppAuthentication(options => { options.Domain = builder.Configuration["Auth0:Domain"]; options.ClientId = builder.Configuration["Auth0:ClientId"]; options.ClientSecret = builder.Configuration["Auth0:ClientSecret"]; }); builder.Services.AddControllersWithViews(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();Step 4: Create AccountControllerCreate a new file Controllers/AccountController.cs: using Auth0.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Auth0MvcApp.Controllers { public class AccountController : Controller { public async Task Login(string returnUrl = "/") { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(returnUrl) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } [Authorize] public async Task Logout() { var authenticationProperties = new LogoutAuthenticationPropertiesBuilder() .WithRedirectUri(Url.Action("Index", "Home")) .Build(); await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } [Authorize] public IActionResult Profile() { return View(); } } }Step 5: Create Profile ViewCreate a new file Views/Account/Profile.cshtml (you may need to create the Views/Account directory first): @{ ViewData["Title"] = "User Profile"; } <div class="row"> <div class="col-md-12"> <h2>@ViewData["Title"]</h2> <div class="row"> <div class="col-md-2"> <img src="@User.FindFirst(c => c.Type == "picture")?.Value" alt="User's profile picture" class="img-fluid rounded-circle" /> </div> <div class="col-md-10"> <h3>@User.Identity.Name</h3> <p><strong>Email:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value</p> <p><strong>Email Verified:</strong> @User.FindFirst(c => c.Type == "email_verified")?.Value</p> <p><strong>User ID:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value</p> </div> </div> <h4 class="mt-4">User Claims</h4> <table class="table"> <thead> <tr> <th>Claim Type</th> <th>Claim Value</th> </tr> </thead> <tbody> @foreach (var claim in User.Claims) { <tr> <td>@claim.Type</td> <td>@claim.Value</td> </tr> } </tbody> </table> </div> </div>Step 6: Update Navigation in _Layout.cshtmlIn Views/Shared/_Layout.cshtml, find the <nav> element and update it to add login/logout links: <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container-fluid"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">SampleMvcApp</a> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> </ul> <ul class="navbar-nav"> @if (User.Identity.IsAuthenticated) { <li class="nav-item"> <a class="nav-link text-dark" asp-controller="Account" asp-action="Profile">@User.Identity.Name</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-controller="Account" asp-action="Logout">Logout</a> </li> } else { <li class="nav-item"> <a class="nav-link text-dark" asp-controller="Account" asp-action="Login">Login</a> </li> } </ul> </div> </div> </nav>⚠️ IMPORTANT: Only replace the <nav> element. Keep all other parts of _Layout.cshtml intact, especially the @RenderBody() call.Step 7: Run the Application dotnet runCRITICAL 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, ClientId, or ClientSecret directly in Program.cs. Always use configuration.2. NEVER use AddAuth0ApiAuthentication for MVC 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.ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION1. 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 MVC apps.
Prerequisites: Before you begin, ensure you have the following installed:
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 ASP.NET MVC application using the Auth0.AspNetCore.Authentication SDK.
1
Create a new project
Create a new ASP.NET Core MVC project for this Quickstart
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:
CLI
Dashboard
Run the following shell command on your project’s root directory to create an Auth0 Application and update your appsettings.json:
Enter a name for your application (e.g., “My MVC App”)
Select Regular Web Application as the application type
Click Create
Go to the Settings tab
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
Configure Callback URLs:In the Settings tab, configure the following URLs:
Important: Only replace the <nav> element. Keep all other parts of _Layout.cshtml intact, especially the @RenderBody() call which is required for rendering page content.
8
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 bar. 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 bar.
CheckpointYou should now have a fully functional Auth0-protected MVC application running on http://localhost:5000. Users can log in, view their profile, and log out.
You can access user profile information through the User property in your controllers or views:
Controllers/AccountController.cs
[Authorize]public IActionResult Profile(){ var user = new { Name = User.Identity.Name, EmailAddress = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value, ProfileImage = User.FindFirst(c => c.Type == "picture")?.Value, UserId = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value }; return View(user);}
The user claims contain standard OIDC information:
Name: User’s display name
Email: User’s email address
Picture: User’s profile picture URL
NameIdentifier (sub): Unique user ID
Customize Login Parameters
You can pass custom parameters to the Auth0 login page:
Controllers/AccountController.cs
public async Task Login(string returnUrl = "/"){ var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(returnUrl) .WithParameter("screen_hint", "signup") // Show signup page .WithParameter("ui_locales", "es") // Set language to Spanish .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);}
Store Tokens for API Calls
If you need to call external APIs on behalf of the user, you can retrieve and store tokens:
Then retrieve the access token in your controller:
Controllers/ApiController.cs
[Authorize]public async Task<IActionResult> CallApi(){ 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(); return View(data);}
Handle Authentication Events
Customize authentication behavior by handling events:
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.
Your application has internet access to reach Auth0
The domain format matches your tenant region (.auth0.com, .us.auth0.com, .eu.auth0.com)
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:
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");});
Middleware order issues
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 UseAuthorizationapp.UseAuthorization();app.MapControllerRoute(...);
A sample application can be found alongside the sourcecode for the SDK:
ASP.NET Core MVC Playgroud App
Includes login, logout, user profile and other examples.
Clone and run:
git clone https://github.com/auth0/auth0-aspnetcore-authentication.gitcd auth0-aspnetcore-authentication/playground/Auth0.AspNetCore.Authentication.Playground# Update appsettings.json with your Auth0 configurationdotnet run