1

I am struggling a little bit to completely understand what is the correct way to implement a windows authentication and role based authorization scheme into an MVC4 application. When the user accesses the (intranet) website I currently have the following method check the user name against the against a database table

    List<string> permissionList = 
PermissionBo.GetUserPermissionsList(PermissionBo.ParseUserName(User.Identity.Name));
    Permissions permissions = new Permissions(permissionList);

Then the following if state adds a role to a user object:

    if (permissions.IsAdmin)
    {
        if(!Roles.RoleExists("UtilitiesToolAdmin"))
        {
            Roles.CreateRole("UtilitiesToolAdmin");
        }
        if(!Roles.IsUserInRole(User.Identity.Name, "UtilitiesToolAdmin"))
        {
            Roles.AddUsersToRole(new string[] { User.Identity.Name }, "UtilitiesToolAdmin");
        }

    }

I feel like this may be an incorrect way to go about implementing this, but I am not sure where I am going wrong. Is this sufficient to begin using the authorize attribute like so:

[Authorize(Roles="UtilitiesToolAdmin")]
public static void Foo()
{
 return "Bar"
}

If not what am I missing?

Pseudonym
  • 2,052
  • 2
  • 17
  • 38
  • Using the Authorize attribute is what you should do. The only time to not use Authorize is if you have to programmatically determine access. – Chris Marisic Oct 08 '14 at 20:39
  • I will try to clear up my question but I know I want to use the Authorize attribute, however I am unclear if it is "correct" to add roles to a user programmatically like I have done – Pseudonym Oct 08 '14 at 20:40

1 Answers1

1

If all you are doing is simple role checking, a custom Role Provider might be a bit of an overkill (Role Providers also provide facilities for managing the roles themselves). What you will end up with is a class full of

throw new NotImplementedException();

Instead, consider creating a custom user principal. The IPrincipal interface defines an IsInRole method that returns a bool. This is where you would put your custom role checks. The advantage of the custom user principal is that now all of the built in ASP.NET role-checking goodies should "just work" as long as you replace the default user principal object with your custom one early enough in the lifecycle.

This SO answer has one of the best examples I've seen of using a custom user principal with an MVC application.

Community
  • 1
  • 1
DVK
  • 2,726
  • 1
  • 17
  • 20