我想在我正在构建的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中读取用户角色,该怎么办?我的应用程序如何知道用户在系统中扮演什么角色?
有人可以帮我这个忙吗?
假设您在会话中存储了用户名和角色:
[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);
. . . .
}
我已经尝试过此方法,但是它说AuthenticationManager类由于某种原因不包含SignIn方法:/
添加
using Microsoft.Owin.Security
参考这是关于类的MSDN页面
AuthenticationManager
Do you have
Microsoft.Owin
,Microsoft.Owin.Security
,Microsoft.Owin.OAuth
in your references?Let us continue this discussion in chat.