身份验证基于 non-MVC Asp.Net 核心 2.x 中的授权 header-scheme 动态

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

我正在创建一个 API,它 不使用 MVC,而是使用通用中间件。应该可以针对 Basic 和 (Jwt) Bearer 方案进行身份验证(我知道 Basic Auth 的安全漏洞)

我可以轻松地在服务中注册这两种方案,但是 app.UseAuthentication 中间件只会尝试根据默认方案进行身份验证(这是故意的,在文档中进行了描述)。可以通过 Authorize 过滤器在 MVC 中为同一端点允许多个方案,但我找不到针对 non-MVC 场景

的简单解决方案

我看到,很多人都在努力实现同样的目标: https://github.com/aspnet/AspNetCore/issues/3620 https://github.com/aspnet/Security/issues/1469

我最终定义了一个基于 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();
});

从2.1开始,可以添加自定义scheme策略,使用AuthenticationSchemeOptions.ForwardDefaultSelector转发默认scheme,参见:https://github.com/aspnet/Security/issues/1469#issuecomment-399239254