问题
I'm creating an API, which does not use MVC, but rather generic middleware(s). It should be possible to be authenticated against both Basic and (Jwt) Bearer scheme (I'm aware of the security flaws of Basic Auth)
I can easily register both schemes in the services, but app.UseAuthentication
middleware will only attempt to authenticate against the default scheme (this is intentional and described in the documentation). Allowing multiple scheme for the same endpoint can be done in MVC by Authorize filter, but I couldn't find a simple solution for non-MVC scenarios
I see, that many people are trying to achieve the same: https://github.com/aspnet/AspNetCore/issues/3620 https://github.com/aspnet/Security/issues/1469
回答1:
I've ended up defining a simple middleware based on https://github.com/aspnet/Security/issues/1469#issuecomment-334982498
app.Use(async (context, next) =>
{
var authHeader = AuthenticationHeaderValue.Parse(context.Request.Headers[HeaderNames.Authorization]);
var schemeName = authHeader?.Scheme ?? string.Empty;
var provider = context.RequestServices.GetService<IAuthenticationSchemeProvider>();
var scheme = await provider.GetSchemeAsync(schemeName);
if (scheme != null)
{
var result = await context.AuthenticateAsync(scheme.Name);
if (result.Succeeded)
{
context.User = result.Principal;
}
}
await next.Invoke();
});
Starting from 2.1, custom scheme policy can be added and forwarding default scheme using AuthenticationSchemeOptions.ForwardDefaultSelector
, see: https://github.com/aspnet/Security/issues/1469#issuecomment-399239254
来源:https://stackoverflow.com/questions/55062245/authentication-based-dynamically-on-authorization-header-scheme-in-non-mvc-asp-n