Authentication and identity
Authentication and identity
Authentication establishes an identity for a request; authorization decides what that identity may do. An authenticated customer is not automatically an administrator. ASP.NET Core authenticates through a named scheme whose handler reads and validates credentials, then produces a ClaimsPrincipal. A claim is an assertion about a subject; it is useful only when its issuer and verification path are trusted.
A ClaimsIdentity is authenticated when its AuthenticationType is nonempty; constructing such an identity in a test does not prove a real person's identity. In a real app a trusted handler supplies the principal. AddAuthentication registers schemes and defaults; UseAuthentication and UseAuthorization must be placed after routing and before protected endpoint execution when ordering is explicit. Challenge asks for authentication (often HTTP 401); forbid denies an authenticated principal (often 403). Cookie schemes can redirect browser pages; in .NET 10 known API endpoints default to 401/403 rather than login redirects. A cookie may carry a protected ticket; browser automatic cookie sending means state-changing endpoints need an appropriate CSRF defense. Secure, HttpOnly and SameSite settings, TLS, expiration and key management serve different purposes. A bearer token is supplied explicitly to a resource server; protect it like a credential. JWT is a token format, not a login protocol or encryption guarantee. A JWT access token requires signature, issuer, audience, lifetime and algorithm validation using trusted issuer keys, including rotation. OAuth addresses delegated authorization; OpenID Connect adds identity to an OAuth flow. An ID token is not an API access token. Use a maintained identity provider and handler, not handwritten token issuance. The offline examples deliberately construct synthetic principals and inspect configuration or protected ticket data; they do not prove an HTTP authentication pipeline.
Baseline: .NET 10 / C# 14 with Microsoft.AspNetCore.App shared framework. All snippets are independent console fixtures, not ByteMind runner code. In an approved isolated environment with a reviewed installed SDK and targeting packs, use dotnet build and dotnet run --no-build in the fixture directory; restore only from approved sources if required. No external service, real user data, account or credential is needed. Expected results are reasoned, not executed; cryptographic random data is not printed.
Identity and role are separate
Two fictional callers have different identity states; a role claim is not a substitute for authentication.
using System.Security.Claims;var guest = new ClaimsPrincipal(new ClaimsIdentity());var reader = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "reader-7"), new Claim(ClaimTypes.Role, "Reader")}, "SyntheticFixture"));Console.WriteLine(guest.Identity!.IsAuthenticated);Console.WriteLine(reader.Identity!.IsAuthenticated);Console.WriteLine(reader.IsInRole("Editor"));Expected output (not executed):
FalseTrueFalseThe reader has an authenticated test identity but lacks the Editor role. No password, cookie or token was accepted.
Register a cookie scheme without starting a server
Inspect only the options of a named cookie scheme. Production cookie names, expiration and SameSite settings must fit the actual app.
using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.DataProtection;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Options;var services = new ServiceCollection();services.AddLogging();services.AddDataProtection().UseEphemeralDataProtectionProvider();services.AddAuthentication("catalog").AddCookie("catalog", o => { o.Cookie.HttpOnly = true; o.Cookie.SecurePolicy = CookieSecurePolicy.Always; o.Cookie.SameSite = SameSiteMode.Lax; o.ExpireTimeSpan = TimeSpan.FromMinutes(20); o.SlidingExpiration = false;});using var provider = services.BuildServiceProvider();var schemes = provider.GetRequiredService<IAuthenticationSchemeProvider>();var scheme = await schemes.GetDefaultAuthenticateSchemeAsync();var settings = provider.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get("catalog");Console.WriteLine(scheme!.Name);Console.WriteLine(settings.Cookie.SecurePolicy);Console.WriteLine(settings.SlidingExpiration);Expected output (not executed):
catalogAlwaysFalseThe default scheme and explicit secure-cookie options are registered. No actual cookie is sent; verify HTTPS and browser behavior in integration tests.
Protect a synthetic authentication ticket
Use an ephemeral Data Protection provider and TicketDataFormat. The protected string is never printed. This is a format exercise, not a login.
using System.Security.Claims;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.DataProtection;var provider = new EphemeralDataProtectionProvider();var format = new TicketDataFormat(provider.CreateProtector("ByteMind.Fixture.Ticket"));var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "reader-7") }, "fixture");var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), new AuthenticationProperties(), "fixture");var protectedTicket = format.Protect(ticket);var restored = format.Unprotect(protectedTicket);Console.WriteLine(restored?.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value);Console.WriteLine(restored?.AuthenticationScheme);var other = new TicketDataFormat(provider.CreateProtector("ByteMind.OtherPurpose"));Console.WriteLine(other.Unprotect(protectedTicket) is null);Expected output (not executed):
reader-7fixtureTrueThe ticket can be restored under its purpose, not under an unrelated purpose. This is not JWT validation, cookie expiration enforcement or proof of account ownership.
Apply the concept
Design an authentication flow for a bookstore with browser pages and a separate API. Specify how the app identifies anonymous requests, which scheme validates each credential, what a forbidden response means, and how cookie CSRF protection differs from API bearer handling.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these fixtures as production security controls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Authentication and identity — knowledge check
Apply the lesson concepts to the following scenarios.
A signed-in reader requests an editor-only resource. What decision failed?
What establishes trust in a JWT access token?
What does a nonempty AuthenticationType prove in a constructed test identity?
What is the default cookie challenge response for a known API endpoint in .NET 10?
Why is CSRF relevant to cookie-authenticated mutations?