-
Notifications
You must be signed in to change notification settings - Fork 588
Multiple authentication shemes for API #1708
Description
I am trying to support multiple authentication methods for my API. Similar to Shawn Wildermuth's post here except I want to support both Cookies, JWT (and also HTTP Basic Auth and Custom Acces Keys*) for single API.
In ASP.NET Core 1.0 this was done by multiple authentication middlewares:
app.UseMiddleware<Luke1988.API.Authentication.CookiesAuthenticationMiddleware>();
app.UseMiddleware<Luke1988.API.Authentication.HttpBasicAuthenticationMiddleware>();
app.UseMiddleware<Luke1988.API.Authentication.JwtBearerAuthenticationMiddleware>();
app.UseMiddleware<Luke1988.API.Authentication.CustomAccessKeysAuthenticationMiddleware>();
where each middleware checks for its Authorization "medium" (cookies, Authorization header), and if present, authenticate, else continue request. Very simple, works like a charm.
When migrating to ASP.NET Core 2.0, this multiple authentication middlewares concept is depreciated and I should use:
services.AddAuthentication()
.AddCookie();
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = _config["Tokens:Issuer"],
ValidAudience = _config["Tokens:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
ValidateLifetime = true
};
});
This simplified setup is not working. When I send Authorization header for JWT, user is not loaded. Authentication is "bypassed".
Addind Authorize attribute with schema to controller makes JWT working, but when I send Cookies in request, Cookies Auth is "bypassed" (this makes sense).
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
public class OrdersController : Controller
No matter what I do, I cannot make multiple authentication schemes on same controller working the way I did in Core 1.0.
Any ideas?
*, ** - both authentication methods are set in customer's project requirements for his internal services integrations.