【发布时间】:2020-08-06 09:51:33
【问题描述】:
我按照下面的教程链接。
我正在尝试了解它是如何工作的,并且我想使用此令牌使用基于角色的身份验证。所以我在Startup.cs 文件中制定了另一项政策,如下所示。
我尝试在控制器中像[Authorize(Policy = "admin")] 或[Authorize(Policy = "ApiUser")] 一样使用它,但每次我尝试使用postman 时都会得到unauthenticated。
我错过了什么?如何根据教程进行基于角色的身份验证?
启动
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
services.AddAuthorization(options =>
options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);
身份验证控制器
// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
if (identity == null)
{
//return null;
return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
}
var id = identity.Claims.Single(c => c.Type == "id").Value;
var user = await _userManager.FindByIdAsync(id);
IList<string> role = await _userManager.GetRolesAsync(user);
var jwt = await Tokens.GenerateJwt(identity, role[0], _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
return new OkObjectResult(jwt);
}
我尝试了所有方法,但都没有工作
[Authorize(Policy = "ApiUser")]
[HttpGet("getPolicy")]
public string GetPolicy()
{
return "policyWorking";
}
[Authorize(Roles = "admin")]
[HttpGet("getAdmin")]
public string GetAdmin()
{
return "adminWorking";
}
[Authorize ]
[HttpGet("getAuthorize")]
public string GetAuthorize()
{
return "normal authorize Working";
}
【问题讨论】:
标签: asp.net asp.net-core asp.net-core-3.1 asp.net-roles asp.net-authentication