Reputation: 2855
I'm using Form authentication in my mvc project.
I've created a CustomRoleProvider and implement two method:
IsUserInRole
and GetRolesForUser
Web.config
<roleManager defaultProvider="CustomRoleProvider" enabled="true">
<providers>
<clear />
<add name="CustomRoleProvider" type="SASS.UI.CustomRoleProvider" connectionStringName="AfterSaleConnection" />
</providers>
</roleManager>
FilterConfig
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new AuthorizeAttribute());
}
CustomRoleProvider
public class CustomRoleProvider : RoleProvider
{
private readonly IUserService _userServices;
public CustomRoleProvider()
{
this._userServices = new UserServices(new Context());
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _userServices.GetUser(username.GetUserId());
if (user.IsAdmin)
return true;
return user.UserAccess.Any(y => (y.Role.ToString().ToLower() == roleName.ToLower()));
}
public override string[] GetRolesForUser(string username)
{
var user = _userServices.GetUser(username.GetUserId());
List<string> accessList = new List<string>();
if (user.UserAccess.Any(x => x.Role == Access.Admin))
{
foreach (Access access in Enum.GetValues(typeof(Access)))
{
accessList.Add(access.ToString().ToLower());
}
return accessList.ToArray();
}
var roles= user.UserAccess.Select(x => x.Role.ToString().ToLower()).ToArray();
return roles;
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string ApplicationName { get; set; }
}
Also I added authorize
attribute above my controller and actions like this:
[Authorize(Roles = "admin")]
public virtual ActionResult List()
{
return View("CustomerList");
}
But when a user request to access for actions that he doesn't have admin
role, he can open it!
I run my project and set a break point in IsUserInRoles
method, But it never fire!
Where's the problem?
Upvotes: 1
Views: 205