我正在使用具有声明身份的cookie身份验证。身份验证正常,但授权失败。
如果登录凭据匹配,这里将存储声明信息。
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, _user[0].UserName.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Role, _user[0].UserRole));
identity.AddClaim(new Claim(ClaimTypes.Email, _user[0].UserEmail));
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
这是startup.cs configurationServices方法中的授权设置
services.AddMvc();
services.AddAuthorization(options => {
options.AddPolicy("Admin", policy => policy.RequireClaim("Admin"));
options.AddPolicy("User", policy => policy.RequireClaim("User"));
});
和控制器
[Authorize(Policy = "Admin")]
public class UserController : Controller
{
//
}
尽管管理员以角色登录,但此授权将重定向到我以访问拒绝页面。这里有什么问题?
答案 0 :(得分:3)
您需要指定声明类型及其应具有的值
services.AddAuthorization(options => {
options.AddPolicy("Admin", policy =>
{
policy.RequireClaim(ClaimTypes.Role, "Admin");
});
options.AddPolicy("User", policy =>
{
policy.RequireClaim(ClaimTypes.Role, "User");
});
});