Labsco
auth0 logo

auth0-aspnetcore-authentication

37

by auth0 · part of auth0/agent-skills

Use when adding cookie-based login, logout, or user profile to an ASP.NET Core MVC, Razor Pages, or Blazor Server web app. Integrates Auth0.AspNetCore.Authentication — use even if the user says "add login to my .NET web app" without naming the package.

🧩 One of 7 skills in the auth0/agent-skills package — works on its own, and pairs well with its siblings.

This is the playbook your agent receives when the skill activates — you don't need to read it to use the skill, but it's here to audit before installing.

Auth0 ASP.NET Core Web App Integration

Add login, logout, and user profile to an ASP.NET Core MVC, Razor Pages, or Blazor Server application using Auth0.AspNetCore.Authentication.


When NOT to Use

  • ASP.NET Core Web APIs with JWT Bearer validation - Use auth0-aspnetcore-api for JWT-protected REST APIs
  • Blazor WebAssembly - Requires OIDC client-side auth; see the Auth0 Blazor WebAssembly quickstart
  • Single Page Applications - Use auth0-react, auth0-vue, or auth0-angular for client-side auth
  • Next.js applications - Use auth0-nextjs which handles both client and server
  • Python web apps - Use auth0-flask for Flask or see the Django quickstart

Blazor Server Variant

For Blazor Server apps, use Razor Pages as auth endpoints - Blazor components cannot perform the HTTP redirects required by OAuth challenges.

Additional Program.cs Setup

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.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddCascadingAuthenticationState();  // Required for Blazor auth state
builder.Services.AddRazorPages();                     // Required for auth endpoints

var app = builder.Build();

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

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

app.Run();

Login Razor Page (Pages/Login.cshtml.cs)

using Auth0.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

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

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

Logout Razor Page (Pages/Logout.cshtml.cs)

using Auth0.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class LogoutModel : PageModel
{
    public async Task OnGet()
    {
        var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
            .WithRedirectUri(Url.Content("~/"))
            .Build();

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

Profile Component (Components/Pages/Profile.razor)

@page "/profile"
@attribute [Authorize]
@using System.Security.Claims

<h1>Profile</h1>

<AuthorizeView>
    <Authorized>
        <div class="row">
            <div class="col-2">
                <img src="@context.User.FindFirst("picture")?.Value"
                     alt="Profile" class="img-fluid rounded-circle" />
            </div>
            <div class="col-10">
                <h3>@context.User.Identity?.Name</h3>
                <p><strong>Email:</strong> @context.User.FindFirst(ClaimTypes.Email)?.Value</p>
            </div>
        </div>

        <h4 class="mt-4">Claims</h4>
        <table class="table">
            <thead><tr><th>Type</th><th>Value</th></tr></thead>
            <tbody>
                @foreach (var claim in context.User.Claims)
                {
                    <tr><td>@claim.Type</td><td>@claim.Value</td></tr>
                }
            </tbody>
        </table>
    </Authorized>
</AuthorizeView>

Update MainLayout.razor Navigation

@using Microsoft.AspNetCore.Components.Authorization

<AuthorizeView>
    <Authorized>
        <a href="/profile">@context.User.Identity?.Name</a>
        <a href="/Logout">Logout</a>
    </Authorized>
    <NotAuthorized>
        <a href="/Login">Login</a>
    </NotAuthorized>
</AuthorizeView>

Routes.razor

Wrap the Router in CascadingAuthenticationState to enable authorization throughout the component tree:

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

Razor Pages Variant

For Razor Pages apps (without Blazor), use AddRazorPages() instead of AddControllersWithViews() in Program.cs. Auth endpoints are the same Login/Logout page models shown in the Blazor Server section. Replace navigation in _Layout.cshtml using the same User.Identity.IsAuthenticated check shown in the MVC section.


Key SDK Methods

Method/PropertyUsagePurpose
AddAuth0WebAppAuthenticationbuilder.Services.AddAuth0WebAppAuthentication(options => { ... })Registers Auth0 cookie-based authentication
LoginAuthenticationPropertiesBuildernew LoginAuthenticationPropertiesBuilder().WithRedirectUri(url).Build()Builds properties for the login challenge
LogoutAuthenticationPropertiesBuildernew LogoutAuthenticationPropertiesBuilder().WithRedirectUri(url).Build()Builds properties for the logout redirect
ChallengeAsyncawait HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, props)Initiates the Auth0 Universal Login redirect
SignOutAsync (Auth0)await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, props)Signs out of Auth0 and redirects to logout URL
SignOutAsync (Cookie)await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)Clears the local session cookie
User.FindFirstUser.FindFirst(c => c.Type == "picture")?.ValueAccesses individual user claims in controllers/views
User.Identity.IsAuthenticated@if (User.Identity.IsAuthenticated)Checks authentication state in views/layouts
[Authorize][Authorize] attribute on controller action or Razor componentProtects routes requiring authentication
AddCascadingAuthenticationStatebuilder.Services.AddCascadingAuthenticationState()Required for Blazor Server auth state propagation

  • auth0-aspnetcore-api - For ASP.NET Core Web APIs with JWT Bearer token validation
  • auth0-express - For server-rendered Express web apps with login/logout sessions
  • auth0-flask - For Flask web applications with session-based auth

Quick Reference

SDK registration:

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

Login action:

var props = new LoginAuthenticationPropertiesBuilder().WithRedirectUri(returnUrl).Build();
await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, props);

Logout action (always call both):

var props = new LogoutAuthenticationPropertiesBuilder().WithRedirectUri(Url.Action("Index", "Home")).Build();
await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, props);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

Route protection:

[Authorize]
public IActionResult Profile() { return View(); }

appsettings.json configuration keys:

  • Auth0:Domain - Auth0 tenant domain (e.g., tenant.us.auth0.com)
  • Auth0:ClientId - Application client ID
  • Auth0:ClientSecret - Application client secret (use user-secrets in development)

Detailed Documentation

  • Setup Guide - Automated setup scripts, credential configuration, Auth0 CLI usage
  • Integration Guide - Protected routes, calling APIs, Blazor patterns, error handling
  • API Reference - Complete SDK configuration, builder options, claims reference

References