AddAuthentication() can register multiple named schemes (e.g., AddCookie("Cookies") and AddJwtBearer("Bearer")), and individual endpoints specify which scheme(s) to use via [Authorize(AuthenticationSchemes = "Bearer")], while a default scheme handles ambiguous cases -- this lets one application serve both browser-based UI (cookie-authenticated) and API endpoints (JWT-authenticated) from the same codebase.
builder.Services.AddAuthentication()
.AddCookie("Cookies")
.AddJwtBearer("Bearer", options => { /* JWT config */ });
[Authorize(AuthenticationSchemes = "Bearer")]
[Route("api/[controller]")]
public class ApiController : ControllerBase { }
[Authorize(AuthenticationSchemes = "Cookies")]
public class AccountController : Controller { }
Real-world example
A traditional MVC web application exposes both server-rendered admin pages (cookie auth) and a JSON API consumed by a separate mobile app (JWT auth) from a single ASP.NET Core project, cleanly separated by authentication scheme per controller.
Likely follow-ups
How is the default authentication scheme chosen when not explicitly specified?
What happens if an endpoint needs to accept either scheme?
ASP.NET Core Middleware & Request PipelineRESTful Web APIs & Controllers
Tokens in localStorage are accessible to any JavaScript running on the page, making them vulnerable to theft via XSS (cross-site scripting) attacks -- a single injected malicious script can read and exfiltrate the token. HttpOnly cookies are inaccessible to JavaScript entirely, protecting against XSS token theft, but introduce CSRF (cross-site request forgery) risk instead, requiring anti-forgery tokens or SameSite cookie attributes as mitigation.
// Vulnerable to XSS if an attacker injects a script:
localStorage.setItem('token', jwt); // any XSS payload can steal this
// HttpOnly cookie: JavaScript cannot read it at all
Response.Cookies.Append("auth_token", jwt, new CookieOptions {
HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict
});
Real-world example
A security review flags a single-page application storing JWTs in localStorage as a critical risk given the app also loads several third-party analytics scripts, recommending a move to HttpOnly cookies with CSRF protection instead.
Likely follow-ups
How does SameSite=Strict mitigate CSRF risk for cookie-stored tokens?
What's the recommended pattern for SPAs needing both XSS and CSRF protection?
CORS & Cross-Origin Resource SharingGlobal Exception Handling & Middleware
ASP.NET Core provides dedicated authentication handler packages (Microsoft.AspNetCore.Authentication.Google, .MicrosoftAccount, etc., or the generic OpenID Connect handler for any compliant provider) that implement the OAuth/OIDC redirect flow, handle token exchange, and map the provider's returned claims into a local ClaimsPrincipal -- letting users 'Sign in with Google' without the application ever handling their Google password directly.
builder.Services.AddAuthentication()
.AddGoogle(options => {
options.ClientId = builder.Configuration["Google:ClientId"];
options.ClientSecret = builder.Configuration["Google:ClientSecret"];
});
// Triggering the flow:
// GET /Account/ExternalLogin?provider=Google
Real-world example
A B2B SaaS platform lets enterprise customers sign in with Microsoft Entra ID (formerly Azure AD) using the OpenID Connect handler, integrating with each customer's existing corporate identity system instead of maintaining separate app-specific passwords.
Likely follow-ups
What's the difference between OAuth 2.0 and OpenID Connect?
How do you link an external login to an existing local account?
Scopes are strings representing specific permissions an application requests (e.g., read:profile, write:orders), and the authorization server presents these to the user during consent, issuing an access token limited to exactly those granted scopes. This lets a resource server enforce fine-grained access control -- an application requesting only read:profile can never use its token to write data, even if it were compromised, limiting the blast radius of a leaked token.
// Requesting narrowly scoped access
GET /authorize?client_id=app123&scope=read:profile+read:email&response_type=code
// Resource server checks scope claim before allowing an action
if (!User.HasClaim("scope", "write:orders")) {
return Results.Forbid();
}
Real-world example
A third-party calendar integration requests only the calendar.readonly scope from Google, meaning even if that integration's token were somehow leaked, an attacker couldn't use it to delete or modify the user's calendar events.
Likely follow-ups
How do you design a good scope taxonomy for a new API?
What's the difference between scopes and roles/claims?
Authentication & Authorization (IdentityJWTOAuth)RESTful Web APIs & Controllers
The middleware extracts the token from the Authorization header, verifies its cryptographic signature against the configured signing key (symmetric secret or asymmetric public key, often fetched dynamically from the issuer's JWKS endpoint), and validates standard claims: expiration (exp, rejecting expired tokens), not-before (nbf), issuer (iss, must match ValidIssuer), and audience (aud, must match ValidAudience) -- failing any check results in a 401 Unauthorized response before the request ever reaches your endpoint code.
A federated identity setup fetches signing keys dynamically from the identity provider's /.well-known/jwks.json endpoint, so the API can validate tokens without hardcoding a static key, automatically picking up key rotations.
Likely follow-ups
What is JWKS and why does dynamic key fetching improve security over hardcoded keys?
Why is ClockSkew tolerance necessary between distributed systems?
Authentication verifies who a user is (commonly via JWT bearer tokens, OAuth/OpenID Connect, or cookies), while authorization determines what an already-authenticated user is permitted to do -- in practice: a user authenticates and receives a token, that token is validated on each subsequent request, and only then does the authorization system check the user's roles or custom policy conditions before granting access to a specific resource. Role-based authorization restricts access using the [Authorize(Roles = "...")] attribute; policy-based authorization defines more flexible, custom rules (like requiring a specific claim value) that can express conditions roles alone can't capture.
An internal admin panel restricts an entire controller to the Admin role via [Authorize(Roles = "Admin")], while a separate age-restricted content endpoint uses a custom "MustBeOver18" policy checking a specific claim, since that particular rule doesn't map cleanly onto a simple role.
Likely follow-ups
What happens if a request fails authorization but authentication succeeded -- what status code is returned, and why?
How would you combine multiple policies or require several claims simultaneously for one endpoint?