asp.net core 2.0授权在身份验证(JWT)之前触发

cda*_*igo 3 c# asp.net-authorization jwt asp.net-core

我正在尝试在asp.net core 2.0应用程序中实现自定义授权策略。

在我的Custom AuthorizationHandler中,我有以下检查:

if (!context.User.Identity.IsAuthenticated)
 {
     this.logger.LogInformation("Failed to authorize user.  User is not authenticated.");
     return Task.CompletedTask;
 }
 // ... More authorization checks
Run Code Online (Sandbox Code Playgroud)

这很有意义,因为未经身份验证的用户无权执行我的控制器操作。

我正在使用JWT承载身份验证,并将其配置如下:

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(cfg =>
    {

        cfg.RequireHttpsMetadata = false;
        cfg.SaveToken = true;

        cfg.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = "<issuer>",
            ValidAudience = "<audience>",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)),
            ValidateLifetime = false
        };

    });
Run Code Online (Sandbox Code Playgroud)

我还在注册我的授权要求和处理程序(请注意,这些注册发生在上面配置了身份验证之后,以及在我致电之前serivces.AddMVC()

services.AddAuthorization(options =>
{
    options.AddPolicy(Constants.AuthorizationPolicies.MyCustomPolicy,
        policy => policy.Requirements.Add(new MyCustomRequirement()));
});
services.AddScoped<IAuthorizationHandler, MyCustomAuthorizationHandler>();
Run Code Online (Sandbox Code Playgroud)

这是我的问题,看来我的授权策略在对jwt令牌进行质询和验证之前正在执行,结果是,由于未对用户进行身份验证,所以我的授权策略失败了。

这是一个示例调用的日志:

Now listening on: http://localhost:60235
Application started. Press Ctrl+C to shut down.
[14:50:57 INF] Request starting HTTP/1.1 GET http://localhost:60235/api/values application/json
[14:51:03 INF] Failed to authorize user.  User is not authenticated.
[14:51:03 INF] Authorization failed for user: null.
[14:51:03 INF] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
[14:51:03 INF] Executing ChallengeResult with authentication schemes ([]).
[14:51:03 INF] Successfully validated the token.
[14:51:03 INF] AuthenticationScheme: Bearer was challenged.
[14:51:03 INF] Executed action AuthorizationTestClient.Controllers.ValuesController.Get (AuthorizationTestClient) in 5819.1586ms
[14:51:03 INF] Request finished in 5961.5619ms 401
Run Code Online (Sandbox Code Playgroud)

如您所见,授权策略首先执行,由于未对用户进行身份验证而失败,然后身份验证质询发生,因此失败。

难道不是这样吗?如何告诉asp.net在授权之前执行身份验证?

Cod*_*ler 11

我也在注册我的授权要求和处理程序(请注意,这些注册发生在上面配置了身份验证之后,并且在我调用serivces.AddMVC()之后

DI容器中服务注册的顺序不是很重要。什么重要的它在中间件登记的先后顺序Startup.Configure方法。您尚未提供此方法的代码,但是我敢打赌您在MVC中间件之后添加身份验证中间件,或者根本不添加它。身份验证中间件应在MVC之前添加,因此请确保您的Startup.Configure外观类似于以下内容:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

查看以下文章以了解更多详细信息: