【问题标题】:Claims in AuthorizationHandlerContext comes empty in HandleRequirementAsyncAuthorizationHandlerContext 中的声明在 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);
}

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

【问题讨论】:

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

标签: authentication .net-core jwt authorization asp.net-core-webapi


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 2021-04-03
    • 2015-05-08
    • 2020-04-02
    • 2015-05-29
    • 1970-01-01
    • 2012-04-29
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多