Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net asp.net-mvc asp.net-mvc-4 c# roles

Implementing role-based authorization using .NET MVC 5

发布于 2020-04-23 13:06:57

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 

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 . . . 
}

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 ??

Can someone help me out with this ?

Questioner
User987
Viewed
54
SᴇM 2016-10-27 18:13

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

    . . . .
}