Authentication based dynamically on Authorization header-scheme in non-MVC Asp.Net Core 2.x

こ雲淡風輕ζ 提交于 2020-03-23 08:55:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!