asp.net core 2.0-基于声明和策略的授权

时间:2018-07-20 12:24:10

标签: c# cookies asp.net-core-mvc authorization claims-based-identity

我正在使用具有声明身份的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
    {
//
    }

尽管管理员以角色登录,但此授权将重定向到我以访问拒绝页面。这里有什么问题?

1 个答案:

答案 0 :(得分:3)

您需要指定声明类型及其应具有的值

services.AddAuthorization(options => {
    options.AddPolicy("Admin", policy =>
        {
            policy.RequireClaim(ClaimTypes.Role, "Admin");
        });
     options.AddPolicy("User", policy =>
        {
            policy.RequireClaim(ClaimTypes.Role, "User");
        });
});