首页 文章

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

提问于
浏览
1

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

在我的自定义AuthorizationHandler中,我有这个检查:

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

这是有道理的,因为未经身份验证的用户未获得我的控制器操作的授权 .

我正在使用JWT bearer auth并将其配置如下:

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
        };

    });

我在上面配置了身份验证,并且在我调用 serivces.AddMVC() 之前:

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

这是我的问题,在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

如您所见,授权策略首先执行,失败,因为用户未经过身份验证,然后发生身份验证质询 .

这不应该是另一种方式吗?如何告知asp.net在授权之前执行身份验证?

2 回答

  • -8

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

    DI容器中的服务注册顺序不是很重要 . is 重要的是 Startup.Configure 方法中的中间件注册顺序 . 您还没有提供此方法的代码,但我敢打赌您在MVC中间件之后添加身份验证中间件或根本不添加它 . 应该在MVC之前添加身份验证中间件,因此请确保您的 Startup.Configure 看起来与此类似:

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

    查看以下文章了解更多详情:

  • 5

    好吧..事实证明这很容易解决 . 我需要在我的Configure方法中调用app.UseAuthentication() . 傻我!

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

相关问题