基本身份验证和AllowAnonymous没有授权标头

Сер*_*шёв 5 c# middleware basic-authentication asp.net-core-mvc

我正在编写一个小型授权服务,它将使用 Net Core 1.1 来使用基本身份验证和 JWT 授权。我采用了 Barry Dorans 的示例作为基本身份验证中间件的基础。问题是,有时我的服务会收到没有授权标头的请求,在这种情况下,我希望允许标记为 [AllowAnonymous] 的操作。

ConfigureServices这是获得授权工作的一部分:

_services.AddAuthorization(o =>
        {
            ClaimOptions authenticatedClaimOptions = new ClaimOptions(CustomClaimTypes.AUTHENTICATED, true);
            o.AddPolicy(Policies.AUTHENTICATED, p => p.RequireClaim(authenticatedClaimOptions.ClaimType, authenticatedClaimOptions.ClaimValue));

            ClaimOptions tenantMemberClaimOptions = new ClaimOptions(CustomClaimTypes.TENANT_MEMBER, true);
            o.AddPolicy(Policies.TENANT_MEMBER, p => p.RequireClaim(tenantMemberClaimOptions.ClaimType, tenantMemberClaimOptions.ClaimValue));

        });

        _services.AddMvcCore(c =>
        {
            AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();

            c.Filters.Add(new AuthorizeFilter(policy));
            // if I uncomment the next line all actions will work as if marked with [AllowAnonymous]
            //c.Filters.Add(new AllowAnonymousFilter());
        })
        .AddApiExplorer()
        .AddJsonFormatters(s =>
        {
            s.ContractResolver = new CamelCasePropertyNamesContractResolver();
            s.NullValueHandling = NullValueHandling.Ignore;
        });
Run Code Online (Sandbox Code Playgroud)

这是我的方法的一部分Configure

var baeh = new BasicAuthenticationEventHandler(loggerFactory.CreateLogger<BasicAuthenticationEventHandler>(), _configurationRoot, securityOptions);

        app.UseBasicAuthenticationMiddleware(new BasicAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge    = true,


            Events = new BasicAuthenticationEvents
            {
                OnValidateCredentials = baeh.ValidateCredentialsHandler,
                OnAuthenticationFailed = baeh.AuthenticationFailedHandler
            }
        });

        app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AutomaticAuthenticate = false,
            AutomaticChallenge = false,
            TokenValidationParameters = jwtParameters,
            SaveToken = true
        });
Run Code Online (Sandbox Code Playgroud)

在我的HandleAuthenticateAsync操作中AuthenticateResult.Skip(),一旦没有检测到授权标头,我就会执行此操作,因此期望 BasicAuthenticationMiddleware 和 JwtBearerMiddleware 都会跳过身份验证,并最终出现在我的[AllowAnonymous]操作中。但每次标头不存在时,我都会进入HandleUnauthorizedAsyncBasicAuthenticationMiddleware 的处理程序。请有人给我解释一下为什么。到目前为止我已经没有任何想法了。

非常感谢您的任何建议。