gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:16:03 24 4
gpt4 key购买 nike

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

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

之后,每个用户都会分配给他一个角色。现在...我的问题是,如何允许或禁止访问我的 .NET MVC 应用程序中的特定 View / Controller 。我偶然发现了这个:

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

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

有人可以帮我解决这个问题吗?

最佳答案

假设您已将用户名和角色存储在 session 中:

[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);

. . . .
}

关于c# - 使用 .NET MVC 5 实现基于角色的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40281330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com