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 ?
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);
. . . .
}
I've tried this method now, but it says that AuthenticationManager class doesn't contains SignIn method for some reason :/
Add
using Microsoft.Owin.Security
referenceHere is MSDN page about
AuthenticationManager
classDo you have
Microsoft.Owin
,Microsoft.Owin.Security
,Microsoft.Owin.OAuth
in your references?Let us continue this discussion in chat.