authentication - AuthorizationHandlerContext 中的声明在 HandleRequirementAsync 中为空

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

我有一个带有 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 token 承载作为 header 。当我尝试从 HandleRequirementAsync 处理程序访问声明时,声明为空。处理程序看起来像:
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 
                                                       FeatureRequirement requirement)
{
  var identity = (ClaimsIdentity)context.User.Identity;
  IEnumerable<Claim> claims = identity.Claims;
  context.Succeed(requirement);
}

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

最佳答案

如果您想拥有 claim 你应该声明 它(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);
    }

关于authentication - AuthorizationHandlerContext 中的声明在 HandleRequirementAsync 中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212147/

相关文章:

javascript - SPA和SSO中无状态身份验证的性能(单点登录)

authentication - IIS/冷融合 : authentication request on anonymous content

c# - VS 代码 : How to copy files to output directory depending on build configurations

javascript - 在哪里可以检索 Cognito 身份池的公钥?

node.js - 从 Google JWT 到使用 React 和 Node.js 访问和刷新 token

wcf - 如何在WCF和WIF中使用JWT token ?

android - 即使我关闭设备,如何保持应用程序 session 打开?

php - 登录验证脚本错误

c# - 如何提取自定义 header 值?

.net-core - 是否有任何理由使用 SaveChangesInterceptor 而不是覆盖 OnBeforeSaveChanges 和 OnAfterSaveChanges?