User permissions on certain views based on roles

2019-08-11 22:45发布

I am using ASP.NET MVC 3. Please excuse my terminology. We assign roles to certain people at work, then we use Windows authentication to determine what roles a user has. Lets say the roles are RoleA, RoleB and RoleC. So now I get a list of roles for a user. Lets says that UserA belongs to RoleA and RoleB. Some of my views need to be authenticated as not everyone can view certain views. Lets say that ViewA can only be viewed by users that belong to roles RoleA and RoleB. How would I do this? What would I need to look into? When a user that does not belong to these roles tries to access the views then he/she should be redirected to an error page.

Also, I need some sort of helper method to check these roles as well to be used in my views to hide/display certain controls. Where is the best place to use this?

Any sample code / articles would be appreciated.

1条回答
Lonely孤独者°
2楼-- · 2019-08-11 22:58
[Authorize(Roles = "RoleA,RoleB")]
public ActionResult Foo()
{
    return View();
}

And if you want to check roles in the view:

@if (User.IsInRole("RoleA"))
{
    <div>This will be visible only to users in RoleA</div>
}
查看更多
登录 后发表回答