Eld*_*ohn 5 authentication authorization jwt .net-core asp.net-core-webapi
我有一个带有 POST 方法的 Web API,如下所示:
[HttpPut]
[Authorize("FeaturePolicy")]
public IActionResult Put()
{
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
启动看起来像这样:
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();
}
Run Code Online (Sandbox Code Playgroud)
我正在从邮递员发送 JWT 令牌承载作为标头。当我尝试从 HandleRequirementAsync 处理程序访问声明时,声明为空。处理程序看起来像:
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
FeatureRequirement requirement)
{
var identity = (ClaimsIdentity)context.User.Identity;
IEnumerable<Claim> claims = identity.Claims;
context.Succeed(requirement);
}
Run Code Online (Sandbox Code Playgroud)
在这里做错了吗?请帮忙!谢谢。
小智 0
如果你想要声明你应该声明它(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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
678 次 |
| 最近记录: |