Use*_*987 7 c# asp.net asp.net-mvc roles asp.net-mvc-4
我想在我正在构建的Web应用程序中实现基于角色的授权.我想象的方法是在我的DB中创建3个表,如下所示:
1. Roles
2. UserRoles (many to many table)
3. Users
Run Code Online (Sandbox Code Playgroud)
之后,每个用户都将分配一个角色.现在......我的问题是,如何允许或禁止访问.NET MVC应用程序中的特定视图/控制器.我偶然发现了这个:
[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
// . . . Enter some payroll . . .
}
Run Code Online (Sandbox Code Playgroud)
Authorize属性似乎将特定控制器/操作限制为特定角色......但是,如果我从UserRoles表中读取用户角色,就像我的情况一样?我的应用程序将如何知道用户在系统中扮演什么角色?
有人可以帮我解决这个问题吗?
让我们假装您已在会话中存储了您的UserName和角色:
[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);
. . . .
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25508 次 |
| 最近记录: |