Question

I'm building an intranet application using Windows authentication and I have pulled my users to my local DB, keeping only the information I need from Active Directory.

I would like to assign roles to my users (Admin or user) and restrict the admin views.

Is there a simple way to do this without going the Identity route? I've looked into it and it seems overkill and honestly rather confusing. Would there be a way to create a utility class which could be used as an annotation and simply restrict views depending on current user role property?

Was it helpful?

Solution

I found a simple solution for those interested. I decided to avoid using any Role Provider altogether because all you really need is a method that authenticate the request and another to check the user's role. In my Global.asax I added the following method, taken from this blog post:

void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    var ctx = HttpContext.Current;
    if (ctx.Request.IsAuthenticated)
    {
        string[] roles = LookupRolesForUser(ctx.User.Identity.Name);
        var newUser = new GenericPrincipal(ctx.User.Identity, roles);
        ctx.User = Thread.CurrentPrincipal = newUser;
    }
}

The only method you have to implement yourself is LookupRolesForUser. Mine looks like this (the Linq will depend on your database structure, I have 3 tables for mine: User, Role and User_Role):

public string[] LookupRolesForUser(string username)
{
    using (MyContext db = new MyContext())
    {
        var user = db.Users.FirstOrDefault(u => u.Username.Equals(username, StringComparison.CurrentCultureIgnoreCase) || u.Email.Equals(username, StringComparison.CurrentCultureIgnoreCase));

        var roles = from ur in user.Roles
                    from r in db.Roles
                    where ur.RoleId == r.RoleId
                    select r.RoleName;
        if (roles != null)
            return roles.ToArray();
        else
            return new string[] { }; ;
    }
}

Then you can use the Authorize annotion in your controllers as such:

 [Authorize(Roles = "Administrator")]
 public class AdminController : BaseController
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top