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

时间:2009-11-13 08:46:22

标签: asp.net authorization oauth roles

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

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

如果我在我的web.config文件中设置<roleManager enabled="false" ...>,则认证模块的指定角色会停留。显然,我想要两全其美。如何使用角色提供程序,但在我的身份验证模块决定时“取消”角色提供程序的效果?

1 个答案:

答案 0 :(得分: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();
        }
    }
相关问题