我有一个带有 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/