AuthorizationHandlerContext 中的声明在 HandleRequirementAsync 中为空

Posted

技术标签:

【中文标题】AuthorizationHandlerContext 中的声明在 HandleRequirementAsync 中为空【英文标题】:Claims in AuthorizationHandlerContext comes empty in HandleRequirementAsync 【发布时间】:2020-03-31 09:19:18 【问题描述】:

我有一个带有这样的 POST 方法的 Web API:

[HttpPut]
[Authorize("FeaturePolicy")]
public IActionResult Put()
             
  return Ok();

启动看起来像这样:

public void ConfigureServices(IServiceCollection services)

   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
   services.AddAuthentications();
   services.AddAuthorization("FeaturePolicy", "featureId");
 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

  if (env.IsDevelopment())
  
    app.UseDeveloperExceptionPage();
  
  else
  
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see   https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
          
    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseAuthentication();

我正在从 Postman 发送 JWT 令牌承载作为标头。当我尝试从 HandleRequirementAsync 处理程序访问声明时,声明为空。处理程序看起来像:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 
                                                       FeatureRequirement requirement)

  var identity = (ClaimsIdentity)context.User.Identity;
  IEnumerable<Claim> claims = identity.Claims;
  context.Succeed(requirement);

这里做错了吗?请帮忙!谢谢。

【问题讨论】:

如果您没有获得成功的身份验证,那么您的上下文将不会包含声明。我的意思是您的问题是无法验证请求。您的请求无权完成 【参考方案1】:

如果你想声明你应该声明它(Jwt的设置)

如下:

   private string generateJwtToken(User user)
    
        // generate token that is valid for 7 days
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        
            Subject = new ClaimsIdentity(new[]  new Claim("id", user.Id.ToString()) ),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        ;
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    

【讨论】:

以上是关于AuthorizationHandlerContext 中的声明在 HandleRequirementAsync 中为空的主要内容,如果未能解决你的问题,请参考以下文章