MCPInstall

auth0-aspnetcore-authentication

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.

Installs
309
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/auth0/agent-skills --skill auth0-aspnetcore-authentication
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads auth0-aspnetcore-authentication automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

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.


Prerequisites

  • ASP.NET Core application (.NET 8 or higher)
  • Auth0 Regular Web Application configured (not an API - must be an Application)
  • If you don't have Auth0 set up yet, use the auth0-quickstart skill first

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

Quick Start Workflow

1. Install SDK

dotnet add package Auth0.AspNetCore.Authentication

2. Configure Credentials

Add Auth0 settings to appsettings.json:

{
  "Auth0": {
    "Domain": "your-tenant.us.auth0.com",
    "ClientId": "your_client_id",
    "ClientSecret": "your_client_secret"
  }
}

For local development, keep secrets out of source control - use dotnet user-secrets to avoid committing ClientSecret:

dotnet user-secrets set "Auth0:Domain" "your-tenant.us.auth0.com"
dotnet user-secrets set "Auth0:ClientId" "your_client_id"
dotnet user-secrets set "Auth0:ClientSecret" "your_client_secret"

Auth0:Domain is your tenant domain (without https://). Auth0:ClientId and Auth0:ClientSecret come from your Auth0 Application settings.

3. Configure Auth0 Dashboard

In your Auth0 Application settings:

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

4. Register Auth0 in Program.cs

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

// Standard middleware...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();    // Must come before UseAuthorization
app.UseAuthorization();     // Critical: order matters

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Critical: UseAuthentication() must come before UseAuthorization(). Reversing these causes silent auth failures where protected routes are never challenged.

5. Create AccountController

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

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

Login does not need [Authorize] - it is the entry point for unauthenticated users. Logout requires [Authorize] to ensure the sign-out only fires for authenticated sessions. Always call both SignOutAsync methods - signing out of only the Auth0 scheme leaves a local cookie; signing out of only the cookie scheme skips the Auth0 logout URL.

6. Create Profile View

Create Views/Account/Profile.cshtml:

@{
    ViewData["Title"] = "User Profile";
}

<div class="row">
    <div class="col-md-2">
        <img src="@User.FindFirst(c => c.Type == "picture")?.Value"
             alt="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>User ID:</strong>
           @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value</p>
    </div>
</div>

<h4 class="mt-4">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>

7. Update Navigation (_Layout.cshtml)

Add login/logout/profile links to your nav bar inside _Layout.cshtml:

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

8. Test the App

dotnet run

Visit http://localhost:5000 and click Login to start the Auth0 login flow.


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.


Common Mistakes

MistakeFix
Hardcoding Domain, ClientId, or ClientSecret in sourceRead from configuration - use builder.Configuration["Auth0:Domain"]; never embed credentials
Committing ClientSecret to source controlUse dotnet user-secrets or environment variables for the client secret - never commit it
UseAuthorization() before UseAuthentication()Must call UseAuthentication() first - wrong order causes auth to never fire
Signing out of only one schemeAlways call both SignOutAsync(Auth0Constants.AuthenticationScheme) and SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)
Adding [Authorize] to the Login actionLogin must be accessible to unauthenticated users - only apply [Authorize] to Logout and Profile
Not configuring Callback URLs in Auth0 DashboardMust add http://localhost:5000/callback to Allowed Callback URLs
Passing Domain with https:// prefixDomain should be the bare domain, e.g., my-tenant.us.auth0.com, not https://my-tenant.us.auth0.com
Not adding AddCascadingAuthenticationState() in BlazorRequired for Blazor Server - without it, AuthorizeView and [Authorize] attributes have no auth context
Using Blazor components for login/logout redirectsBlazor components cannot perform HTTP redirects - use Razor Pages (/Login, /Logout) for auth endpoints
Not adding AddRazorPages() and MapRazorPages() in BlazorLogin and Logout Razor Pages won't be routed without these registrations
Using Auth0.AspNetCore.Authentication.Api for web appsThat package is for JWT-protected APIs - use Auth0.AspNetCore.Authentication for session-based web apps
Using AddJwtBearer instead of AddAuth0WebAppAuthenticationAddJwtBearer is for stateless API auth - session-based web apps require AddAuth0WebAppAuthentication
Not creating Views/Account/ directory for Profile viewMVC requires the directory to exist before creating the view

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

Related Skills

  • 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

FAQ

What does the auth0-aspnetcore-authentication skill do?

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.

How do I install auth0-aspnetcore-authentication?

Run npx skills add https://github.com/auth0/agent-skills --skill auth0-aspnetcore-authentication in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/auth0-aspnetcore-authentication/ (personal) or .claude/skills/auth0-aspnetcore-authentication/ (project).

Which AI agents can use auth0-aspnetcore-authentication?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is auth0-aspnetcore-authentication safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains auth0-aspnetcore-authentication?

It is published by auth0 in auth0/agent-skills, and it is an official skill from the maker of the technology it covers. It has 309 recorded installs.

More from auth0/agent-skills

View all →

auth0

auth0/agent-skills

Use when adding, fixing, or improving how an app authenticates users or protects an API, or when using or configuring any Auth0 feature — signing users in and out, sessions and tokens, guarding routes and endpoints, MFA, passwordless passkey login (WebAuthn), SSO, Organizations, RBAC, custom domains, Universal Portals for hosted account and organization self-service, or Universal Login branding. Also use to audit a tenant's health, security, and plan fit (CheckMate), to debug why an auth flow fails, to migrate from another auth provider, or to set up the Vercel native integration. Covers any web, mobile, or backend framework and every Auth0 SDK, tool, and API. Use even if the user never mentions Auth0.

Backend & APIs5.3K installs

auth0-quickstart

auth0/agent-skills

Use when adding Auth0 authentication to any app and unsure which SDK or skill to use. Detects the project's framework and routes to the right setup workflow — use this as the entry point even if the user just says "add login to my app" or "set up Auth0" without naming a framework.

OfficialAI & Agents2.7K installs

auth0-nextjs

auth0/agent-skills

Use when adding Auth0 login, logout, protected pages, or middleware to a Next.js application. Supports App Router and Pages Router with @auth0/nextjs-auth0 — use even if the user says "add login to my Next.js app" or "protect my Next.js routes".

OfficialFrontend & Design1.6K installs

auth0-react

auth0/agent-skills

Use when adding Auth0 login, logout, protected routes, or user sessions to a React SPA. Integrates @auth0/auth0-react — use even if the user says "add login to my React app" or "protect my React routes" without naming the SDK.

OfficialFrontend & Design1.5K installs

auth0-react-native

auth0/agent-skills

Use when adding Auth0 login, logout, or biometric auth to a bare React Native app (not Expo). Integrates react-native-auth0 with native deep linking.

OfficialFrontend & Design963 installs

auth0-express

auth0/agent-skills

Use when adding session-based login, logout, or protected routes to an Express.js web application. Integrates express-openid-connect — use even if the user says "add login to my Express app" or "protect my Express routes".

OfficialBackend & APIs816 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs