Authentication
Authentication answers the question "who are you?". It turns the credentials attached to a request — a cookie, a bearer token, a client certificate — into a user identity. Deciding what that user may do is a separate step called authorization, covered in the next lesson.
In ASP.NET Core the result of authentication is a ClaimsPrincipal, available as HttpContext.User. A principal holds one or more identities, and each identity is a bag of claims: small name/value facts such as sub = 42, name = ada or role = admin.
Schemes and handlers
You register one or more authentication schemes. Each scheme has a name and a handler that knows how to read one kind of credential:
| Scheme | Package | Credential | Typical client |
|---|---|---|---|
| Cookie | built in (Microsoft.AspNetCore.Authentication.Cookies) |
encrypted .AspNetCore.Cookies cookie |
browser apps, Razor Pages, MVC |
| JWT bearer | Microsoft.AspNetCore.Authentication.JwtBearer |
Authorization: Bearer <token> header |
SPAs, mobile apps, service-to-service |
| Identity bearer | built into ASP.NET Core Identity | opaque token from /login |
quick APIs with their own user store |
| OpenID Connect | Microsoft.AspNetCore.Authentication.OpenIdConnect |
redirect to an external identity provider | "Sign in with Microsoft/Google/Entra ID" |
The authentication middleware (app.UseAuthentication()) runs the default scheme on every request and fills in HttpContext.User. If no valid credential is present the user is simply anonymous — authentication alone never rejects a request.
JWT bearer authentication
A JSON Web Token is three base64url parts joined by dots: a header, a payload of claims and a signature. The server only needs the signing key (or the issuer's public keys) to check that nobody tampered with it.
$ dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerusing System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "https://login.example.com",
ValidAudience = "notes-api",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Public endpoint");
app.MapGet("/me", (ClaimsPrincipal user) =>
new { name = user.Identity!.Name, claims = user.Claims.Count() })
.RequireAuthorization();
app.Run();Since .NET 7, when only one scheme is registered it automatically becomes the default, so AddAuthentication() needs no argument. AddJwtBearer also reads settings from the Authentication:Schemes:Bearer configuration section, which is what dotnet user-jwts writes to during development:
$ dotnet user-jwts create --name ada --role admin
$ curl -i localhost:5000/me
$ curl -s localhost:5000/me -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."New JWT saved with ID '1f0c6a2e'.
Name: ada
Roles: [admin]
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
HTTP/1.1 401 Unauthorized
Content-Length: 0
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
WWW-Authenticate: Bearer
{"name":"ada","claims":9}
The 401 with WWW-Authenticate: Bearer is the challenge: the handler telling the client which kind of credential it expects.
What a signature really checks
The idea behind a signed token is easy to rebuild in plain C#: hash the header and payload with a secret key using HMAC-SHA256 and compare. Change one character of the payload and the signature no longer matches.
using System;
using System.Security.Cryptography;
using System.Text;
byte[] key = Encoding.UTF8.GetBytes("a-demo-secret-key-that-is-32-bytes!");
string B64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
string Sign(string data)
{
using var hmac = new HMACSHA256(key);
return B64Url(hmac.ComputeHash(Encoding.UTF8.GetBytes(data)));
}
string header = B64Url(Encoding.UTF8.GetBytes("{\"alg\":\"HS256\",\"typ\":\"JWT\"}"));
string payload = B64Url(Encoding.UTF8.GetBytes("{\"sub\":\"42\",\"name\":\"ada\",\"role\":\"admin\"}"));
string token = quot;{header}.{payload}.{Sign(header + "." + payload)}";
bool Verify(string jwt)
{
string[] parts = jwt.Split('.');
return parts.Length == 3 && Sign(parts[0] + "." + parts[1]) == parts[2];
}
Console.WriteLine(quot;Token parts: {token.Split('.').Length}");
Console.WriteLine(quot;Original valid? {Verify(token)}");
string forgedPayload = B64Url(Encoding.UTF8.GetBytes("{\"sub\":\"42\",\"name\":\"ada\",\"role\":\"owner\"}"));
string forged = quot;{header}.{forgedPayload}.{token.Split('.')[2]}";
Console.WriteLine(quot;Forged valid? {Verify(forged)}");Token parts: 3
Original valid? True
Forged valid? False
The real handler also checks expiry (exp), issuer (iss) and audience (aud), and uses a constant-time comparison. Never write your own token validation in production — but knowing what it does helps you debug a 401.
Note: A JWT payload is only encoded, not encrypted. Anyone holding the token can read its claims, so never put secrets in it.
Cookie authentication
Browser apps usually use cookies. After the user proves who they are, you call SignInAsync; the handler serializes the principal into an encrypted, signed cookie (protected by the Data Protection API).
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/login";
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
});
app.MapPost("/login", async (HttpContext http, string user) =>
{
// ...check the password first!
var identity = new ClaimsIdentity(
[new Claim(ClaimTypes.Name, user)],
CookieAuthenticationDefaults.AuthenticationScheme);
await http.SignInAsync(new ClaimsPrincipal(identity));
return Results.Ok();
});
app.MapPost("/logout", async (HttpContext http) =>
{
await http.SignOutAsync();
return Results.NoContent();
});For a cookie scheme, the challenge is a 302 redirect to LoginPath for page requests rather than a bare 401.
ASP.NET Core Identity in one line
If you need user registration, password hashing, lockout and tokens without writing them yourself, use Identity with EF Core. Since .NET 8, AddIdentityApiEndpoints plus MapIdentityApi gives an API ready-made /register, /login, /refresh and more:
builder.Services.AddDbContext<AppDb>(o => o.UseSqlite("Data Source=app.db"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>()
.AddEntityFrameworkStores<AppDb>();
builder.Services.AddAuthorization();
var app = builder.Build();
app.MapIdentityApi<IdentityUser>();$ curl -s -X POST localhost:5000/register -H "Content-Type: application/json" -d '{"email":"ada@example.com","password":"Passw0rd!"}' -w "%{http_code}\n"
$ curl -s -X POST localhost:5000/login -H "Content-Type: application/json" -d '{"email":"ada@example.com","password":"Passw0rd!"}'200
{"tokenType":"Bearer","accessToken":"CfDJ8Kx...","expiresIn":3600,"refreshToken":"CfDJ8Kx..."}
The access token is an opaque, Data-Protection-protected bearer token (not a JWT); send it back as Authorization: Bearer ….
Claims in plain C#
ClaimsPrincipal lives in System.Security.Claims, which is part of the base library, so you can explore it without a web server:
using System;
using System.Linq;
using System.Security.Claims;
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, "42"),
new Claim(ClaimTypes.Name, "ada"),
new Claim(ClaimTypes.Role, "admin"),
new Claim(ClaimTypes.Role, "editor"),
new Claim("department", "research"),
}, authenticationType: "Bearer");
var user = new ClaimsPrincipal(identity);
var anonymous = new ClaimsPrincipal(new ClaimsIdentity());
Console.WriteLine(quot;Name: {user.Identity?.Name}");
Console.WriteLine(quot;Authenticated: {user.Identity?.IsAuthenticated}");
Console.WriteLine(quot;Anonymous authenticated: {anonymous.Identity?.IsAuthenticated}");
Console.WriteLine(quot;Is admin: {user.IsInRole("admin")}");
Console.WriteLine(quot;Department: {user.FindFirst("department")?.Value}");
Console.WriteLine(quot;Roles: {string.Join(", ", user.FindAll(ClaimTypes.Role).Select(c => c.Value))}");Name: ada
Authenticated: True
Anonymous authenticated: False
Is admin: True
Department: research
Roles: admin, editor
An identity counts as authenticated only when it has an authenticationType — exactly what the handlers set.
Tip: Always serve authenticated apps over HTTPS. Cookies and bearer tokens sent over plain HTTP can be stolen and replayed.
Test yourself
What does the authentication middleware do when a request has no credentials?
- Returns 401 immediately
- Returns 403 immediately
- Leaves the user anonymous and lets the request continue
- Redirects to /login
Which response header accompanies a 401 from the JWT bearer handler?
LocationWWW-Authenticate: BearerSet-CookieRetry-After
Is the payload of a JWT secret?
- Yes, it is encrypted with the signing key
- Only the
subclaim is hidden - Yes, if HTTPS is used
- No — it is base64url-encoded, so anyone with the token can read it