Advertisement
Advanced .NET, Authentication & Authorization (Identity, JWT, OAuth)

How does ASP.NET Core support multiple authentication schemes simultaneously (e.g., cookies for a web UI and JWT for an API in the same application)?

Short answer

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…

Save .NET mock interview
Advertisement
AModel answer
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?
Related topics