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