温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Implementing role-based authorization using .NET MVC 5
asp.net asp.net-mvc asp.net-mvc-4 c# roles

c# - 使用.NET MVC 5实现基于角色的授权

发布于 2020-04-26 16:52:43

我想在我正在构建的Web应用程序中实现基于角色的授权。我想象的实现方式是在数据库中创建3个表,如下所示:

1. Roles
2. UserRoles (many to many table)
3. Users 

之后,将为每个用户分配一个角色。现在...我的问题是,如何允许或禁止访问.NET MVC应用程序中的特定视图/控制器。我偶然发现了这一点:

[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
    //  . . . Enter some payroll . . . 
}

Authorize属性似乎将特定的控制器/动作限制为特定的角色...但是,如果像我这样从表UserRoles中读取用户角色,该怎么办?我的应用程序如何知道用户在系统中扮演什么角色?

有人可以帮我这个忙吗?

查看更多

提问者
User987
被浏览
48
SᴇM 2016-10-27 18:13

假设您在会话中存储了用户名和角色:

[AllowAnonymous]
[HttpGet]
public ActionResult Login()
{
    . . . .

    string userName = (string)Session["UserName"];
    string[] userRoles = (string[])Session["UserRoles"];

    ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

    userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

    identity.AddClaim(new Claim(ClaimTypes.Name, userName));

    AuthenticationManager.SignIn(identity);

    . . . .
}