I am developing a MVC 5 application with custom role provider, but it seems that the Authorize Attribute never call my customer role provider, my code is as below:
namespace SIMSPortal.Models
{
public class MyCustomRoleProvider:RoleProvider
{
public override string[] GetRolesForUser(string username)
{
using(var usersContext = new SchoolPortalEntities())
{
var user = usersContext.login_details.SingleOrDefault(u => u.user_id == username);
if(user == null)
return new string[] { };
return user.UserInRoles == null ? new string[] { } :
user.UserInRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
}
}
}
}
public override bool IsUserInRole(string username, string roleName)
{
using(var usersContext = new SchoolPortalEntities())
{
var user = usersContext.login_details.SingleOrDefault(u => u.user_id == username);
if(user == null)
return false;
return user.UserInRoles != null && user.UserInRoles.Select(
u => u.Role).Any(r => r.RoleName == roleName);
}
}
my config file:
<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="false">
<providers>
<clear />
<add name="CustomRoleProvider" type="SIMSPortal.Models.MyCustomRoleProvider" />
</providers>
</roleManager>
However, my custom role provider is in Model folder, and i am using EF DB first approach, I am able to call my custom role provider method with following code within my controller:
String[] roles = Roles.GetRolesForUser(userId);
However any controller where [Authorize] attribute is being used, users are always redirect to the login page, even when user login and role are both valid. This same code works fine using MVC4. Please help