Advertisement
Intermediate ASP.NET Core, Authentication

How do you configure ASP.NET Core to support multiple authentication schemes simultaneously, such as both cookies for a web UI and JWT for an API?

Short answer

Register multiple named schemes via chained AddCookie/AddJwtBearer calls, then specify which scheme(s) apply per endpoint using [Authorize(AuthenticationSchemes = "Bearer")] on API controllers and a separate scheme for UI controllers -- a default scheme handles requests that…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Register multiple named schemes via chained AddCookie/AddJwtBearer calls, then specify which scheme(s) apply per endpoint using [Authorize(AuthenticationSchemes = "Bearer")] on API controllers and a separate scheme for UI controllers -- a default scheme handles requests that don't explicitly specify one, letting a single application serve both browser-rendered pages and a JSON API with appropriately different authentication mechanisms.
builder.Services.AddAuthentication()
    .AddCookie("Cookies")
    .AddJwtBearer("Bearer");

[Authorize(AuthenticationSchemes = "Bearer")]
[Route("api/[controller]")]
public class ApiController : ControllerBase { }

[Authorize(AuthenticationSchemes = "Cookies")]
public class AccountController : Controller { }
Real-world example
A hybrid application serves server-rendered admin pages via cookie authentication and a separate mobile-app-facing JSON API via JWT bearer authentication, both from the same ASP.NET Core project, cleanly separated by scheme per controller.
Likely follow-ups
  • How is the default scheme selected when an endpoint doesn't specify one?
  • What happens if a request presents credentials for the wrong scheme?
Related topics