RoleProvider 不适用于服务器上的自定义 IIdentity 和 IPrincipal



我正在使用自定义IIdentity,并通过此处所述的EF 4.3在我的ASP.NET MVC应用程序中IPrincipal(并遵循接受答案的解决方案)。另外,我有一个自定义RoleProvider.在本地(使用 IIS Express ),它目前工作。但是现在,当我在真实主机上上传应用程序时,似乎所有用户都扮演"admin"角色!例如,我创建了一个不在角色"admin"中的用户,但它可以访问所有受保护的页面(需要"admin"角色)。例如 Role.IsUserInRole总是返回true .请问你知道吗?你可以帮我吗?在IIS中我应该做任何设置吗?

我解释了该解决方案,它对我有用。我现在不知道,也许你应该回滚到AuthenticateRequest事件。如果要尝试这种方式,则必须从项目中完全删除RoleManagerModule。试试这个,让我知道是否有效或否:

// in your module:
public void Init(HttpApplication context) {
    _application = context;
    // rollback this line:
    _application.AuthenticateRequest += ApplicationAuthenticateRequest;
}
// and in web.config
<!-- in system.web section: -->
</system.web>
  <!-- other stufs -->
  <httpModules>
    <remove name="RoleManager"/>
  </httpModules>
</system.web>
<!-- and in system.webServer section: -->
<system.webServer>
  <!-- other stufs -->
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="RoleManager"/>
  </modules>
<system.webServer>

如果你想继续使用默认的角色管理器,那就很难了。我尝试通过从默认值派生来创建自己的角色管理器,但没有任何运气。经过 2 天的尝试,我最终为 RolePrincipal 创建了一些扩展方法:

public static bool IsEmployee(this RolePrincipal principal)
{
    if (IsAuthenticated())
        return principal.IsInRole("Employee");
    return false;
}
public static bool IsAdmin(this RolePrincipal principal)
{
    if (IsAuthenticated())
        return principal.IsInRole("Admin");
    return false;
}

创建了一个新的 WebViewPage 类:

public abstract class BaseViewPage : WebViewPage
{
    public virtual new RolePrincipal User
    {
        get
        {
            if (base.User == null)
                return null;
            return (RolePrincipal)base.User; //Hard casting: If it goes wrong, it better goes wrong here
        }
    }
}
public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual new RolePrincipal User
    {
        get
        {
            if (base.User == null)
                return null;
            return (RolePrincipal)base.User; //Hard casting: If it goes wrong, it better goes wrong here
        }
    }
}

修改了视图文件夹中的 web.config:

<pages pageBaseType="MyCompany.MyProject.BaseViewPage">

我所有的控制器都派生自我的基本控制器:

public abstract class BaseController : Controller
{
    protected virtual new RolePrincipal User
    {
        get { return HttpContext.User as RolePrincipal; }
    }
}

缺点是这些方法每次被调用时都会查询我的数据库。顺便说一句,我正在使用 MVC 4

希望这对任何人有帮助

最新更新