使用.NET MVC 5实现基于角色的授权 [英] Implementing role-based authorization using .NET MVC 5

查看:66
本文介绍了使用.NET MVC 5实现基于角色的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to implement a role-based authorization in my web application that I'm building. The way I imagined to make this is to create 3 tables in my DB like following:

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

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

After that each user would have a role assigned to him. Now... My question is, How do I permit or forbid access to specific views/controllers inside my .NET MVC application. I've stumbled upon this:

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

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

The Authorize property seems to be limiting the specific controllers/actions to specific roles... But what if I read the user roles from the table UserRoles like in my case?? How is my application gonna know what role does the User have on the system ??

有人可以帮我吗?

推荐答案

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

Lets pretend you have stored your UserName and Roles in 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);

    . . . .
}

这篇关于使用.NET MVC 5实现基于角色的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆