首页 > 解决方案 > 具有基本和 JWT 授权和自定义策略的 ASP.NET Core 3.1

问题描述

我需要在我的 ASP.NET Core 3.1 应用程序中同时拥有 JWT 和基本授权。

这是我的启动配置:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.ApiAuthenticationScheme;
    ...
});
    
services.AddAuthorization(options =>
{
  options.AddPolicy("BasicAuth", policyBuilder =>
     {
         policyBuilder.Requirements.Add(new BasicAuthenticationRequirement());
     });
    
  options.AddPolicy("Customer", policyBuilder =>
      {
         policyBuilder.AuthenticationSchemes.Add(JwtBearerDefaults.ApiAuthenticationScheme);
         policyBuilder.RequireRole("Customer");
      });
});

还 :

 services.AddTransient<IAuthorizationHandler, BasicAuthenticationHandler>();

我需要添加BasicAuthenticationHandler,因为我需要访问IHttpContextAccessor

 public BasicAuthenticationHandler(IHttpContextAccessor httpContextAccessor)
 {
 }

但这里的问题是,对于每个要授权的请求,即使它有 [Authorize(Policy = "Customer")] 它也不会考虑“JwtBearer”并跳过授权并运行操作。

更新

尽管它自己的操作具有 [Authorize] 属性,但控制器具有 [AllowAnonymous] 属性,当我将其从控制器中删除并让操作具有 [Authorize] 时,它起作用了。

.NET Core 覆盖特定操作的控制器级别授权属性

标签: asp.net-corejwtbasic-authentication

解决方案


推荐阅读