I have an MVC app and I wrote a custom roleprovider for it as shown:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using VectorCheck.Models;
namespace VectorCheck.Security
{
public class MyRoleProvider : RoleProvider
{
private VectorCheckRepository<User> _repository { get; set; }
public MyRoleProvider()
{
_repository = new VectorCheckRepository<User>();
}
public MyRoleProvider(VectorCheckRepository<User> repository)
{
_repository = repository;
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
var user = _repository.GetUser(username);
return new string[] { user.Role.Name };
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUser(username);
return string.Compare(user.Role.Name, roleName, true) == 0;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
This works really well with restricting access to controllers and actions using:
[Authorize(Roles = "Administrator")]
above the controller or action.
I also want restricted access to some things in the view though using:
HttpContext.Current.User.IsInRole("Administrator")
This method isn’t part of my roleprovider though so isn’t getting overridden.
Does anyone know how to do it for this method as well?
If you’ve hooked your RoleProvider as the role provider for the application in web.config, then this should work automatically; the framework will create a
RolePrincipalfor an authenticated user at the start of the request that will call theGetRolesForUsermethod on your role provider, passing the name from theIIdentityas the user name.The framework implementation of
RolePrincipal‘sIsInRole(string role)method is something like this (I’ve added comments)Set a breakpoint inside of your RoleProvider
GetRolesForUsermethod to ensure that it is being called correctly and also inspect theIPrincipal(HttpContext.Current.User) to ensure that it is of typeRolePrincipalfor an authenticated user.