本文介绍了动态验证基于非MVC Asp.Net Core 2.x中的Authorization标头方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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

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

I see, that many people are trying to achieve the same:https://github.com/aspnet/AspNetCore/issues/3620https://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开始,可以添加自定义方案策略并使用AuthenticationSchemeOptions.ForwardDefaultSelector转发默认方案,请参见: https://github.com/aspnet/Security/issues/1469#issuecomment-399239254

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

这篇关于动态验证基于非MVC Asp.Net Core 2.x中的Authorization标头方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:53