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)
{
//throw new NotImplementedException();
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();
}
}
}
}
my config file:
<add key="PreserveLoginUrl" value="true" />
<add key="enableSimpleMembership" value="false" />
<add key="autoFormsAuthentication" value="false" />
</appSettings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Login/UserLogin" timeout="2880" />
</authentication>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<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.
How can I make my Authorize Attribute, call my Custom Role Provider?
u.user_id == username
?? surely it should beu.username == username
oru.user_id == userId
– Callum LiningtonSchoolPortalEntities
implementation andlogin_details
type's implementation? – Callum Linington