首页 文章

RoleProvider不能在服务器上使用自定义IIdentity和IPrincipal

提问于
浏览
4

我在我的 ASP.NET MVC 应用程序中通过 EF 4.3 使用自定义 IIdentityIPrincipal 作为expalined here(并按照接受的答案解决方案) . 另外,我有一个自定义 RoleProvider . In local (using IIS Express), it works currectly . 但现在,当我在真实主机上传应用程序时,似乎所有用户都处于 "admin" 角色!例如我创建了一个不在角色 "admin" 中的用户,但它可以访问所有受保护的页面(需要 "admin" 角色) . 例如 Role.IsUserInRole 始终返回 true . 你有什么想法吗?你能帮助我吗?在 IIS 我有什么设置吗?

2 回答

  • 0

    我解释了这个解决方案,它对我有用 . 我现在不行,可能你应该回滚到 AuthenticateRequest 事件 . 如果你想尝试这种方式,你必须从你的项目中完全删除 RoleManagerModule . 尝试这个,让我知道是否工作或nop:

    // 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>
    
  • 5

    如果您想继续使用默认的RoleManager,那就很难了 . 我尝试通过派生默认值来创建我自己的RoleManager,没有任何运气 . 经过两天的尝试,我最终为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
            }
        }
    }
    

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

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

    我的所有控制器都来自我的BaseController:

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

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

    希望这有助于任何人

相关问题