【发布时间】:2019-06-17 18:31:26
【问题描述】:
我正在为 asp.net core webapi 实现基于角色的身份验证。我几乎遵循了这个教程。 https://medium.com/@engr.mmohsin/asp-net-core-2-0-webapi-jwt-role-based-authentication-authorization-with-custom-tables-and-identity-401c898d9ef1
我用管理账户[Authorize(Roles = "Manager")]登录后总是未经授权返回。
在控制器类中
[Route("api/[controller]")]
[Authorize(Roles = "Manager")]
在服务类的登录方法中生成令牌
var claims = new[] {
new Claim("Name", user.Name),
//few other claims
new Claim(ClaimTypes.Role, user.Role.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
在startup.cs中
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
有人,请解释一下这段代码的问题是什么?
已解决:发生这种情况没有到达代码 app.UseAuthentication()
【问题讨论】:
标签: c# authentication asp.net-core user-roles