首页 文章

如何防止RoleProvider覆盖自定义角色?

提问于
浏览
2

我有一个自定义角色提供程序,它从数据库中获取用户所属的角色 . 我还在我的web.config的httpModules中注册了一个自定义身份验证模块,它会嗅探传入的HTTP请求,并且(如果是OAuth签名请求)设置HttpContext.Current.User属性来模拟用户,并且它设置的IPrincipal包括所有用户的角色,以及一个名为“委托”的额外角色 .

问题是,在我设置自定义IPrincipal之后,显然ASP.NET仍然调用我的自定义角色提供程序,然后将IPrincipal重置为仅具有该用户的标准角色的IPrincipal .

如果我在我的web.config文件中设置 <roleManager enabled="false" ...> ,验证模块's assigned roles stick. Obviously though, I want the best of both worlds. How can I use the role provider, but 2570787 the role provider'会在我的身份验证模块决定时生效?

1 回答

  • 1

    事实证明,在身份验证http模块的Init方法中,我可以找到 RoleManager ,然后挂钩一个事件,让我有权否决它是否完成其重要工作:

    public void Init(HttpApplication context) {
            var roleManager = (RoleManagerModule)context.Modules["RoleManager"];
            roleManager.GetRoles += this.roleManager_GetRoles;
        }
    
        private void roleManager_GetRoles(object sender, RoleManagerEventArgs e) {
            if (this.application.User is OAuthPrincipal) {
                e.RolesPopulated = true; // allows roles set in AuthenticationRequest to stick.
            }
        }
    
        private void context_AuthenticateRequest(object sender, EventArgs e) {
            if (/*oauth request*/) {
                HttpContext.Current.User = CreateOAuthPrincipal();
            }
        }
    

相关问题