我在我的MVC3应用程序中使用用户和角色的自定义成员资格。我有自定义用户/角色类。我为此扩展了RoleProvider和MembershipProvider类。
我的应用程序中似乎有一些角色丢失,我的授权[Roles ='xyz']属性无法正常工作并尝试重定向到Account / LogOn。当我的用户登录应用程序时,我所做的只是
if (ModelState.IsValid)
{
if (MyCustomSecurity.Login(model.UserName, model.Password, model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
--other stuff
}
MyCustomSecurity.Login方法基本上在数据库中查找用户,如果有效则返回true值。
在尝试使用我的应用程序调试问题时,我遇到了以下链接
http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF ASP.NET MVC Forms Authentication + Authorize Attribute + Simple Roles
我是否还应该覆盖此链接中提到的FormsAuthentication_OnAuthenticate()?或者RoleProvider扩展类是否解决了这个问题? 谢谢
答案 0 :(得分:0)
如果您在AuthorizeAttribute中使用角色,并且角色是您自己的类,那么您需要覆盖RoleProvider,尤其是方法GetRolesForUser:
public class CustomRoleProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
// put your logic to discover which roles the user has
}
}
执行此操作后,您必须在Web.Config中注册CustomRoleProvider:
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear/>
<add name="CustomRoleProvider" type="%YOURNAMESPACE%.CustomRoleProvider" />
</providers>
</roleManager>