IsInRole具有ASP.NET MVC 5的自定义WebForms身份验证

时间:2014-05-28 18:26:46

标签: asp.net-mvc forms-authentication asp.net-mvc-5

我正在尝试在ASP.NET MVC 5应用程序中实现自定义Forms身份验证,但我之前没有这样做并需要一些帮助。我没有使用会员提供商,但已经跟踪(部分)http://tech.pro/tutorial/1216/implementing-custom-authentication-for-aspnet。所以我使用CustIdentity和CustPrincipal。

这是来自Global.asax.cs的Application_AuthenticateRequest:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
        var identity = new CustIdentity(ticket);
        var principal = new CustPrincipal(identity);
        HttpContext.Current.User = principal;
    }
}

到目前为止工作正常,我可以在上述方法结束时成功调用HttpContext.Current.User.IsInRole(" Admin")。

但是,当我从一个视图中尝试User.IsInRole(" Admin")时,我得到:'你必须调用" WebSecurity.InitializeDatabaseConnection"在调用" WebSecurity"的任何其他方法之前的方法类'由于我不使用成员资格提供程序,因此不应该应用WebSecurity.InitializeDatabaseConnection(我已经安装了SQL用户表等)。

所以我试试

var user = User as CustPrincipal;
if (user != null && user.IsInRole("Admin"))
....

但是用户不能转换为CustPrincipal,因此始终返回null。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

我通过在web.config中注释掉这一部分来实现这一点:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
    <providers>
      <clear />
      <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
    </providers>
</roleManager>-->

似乎我的CustPrincipal被SimpleRoleProvider覆盖了。我从这篇文章得到了这个解决方案: RoleProvider dosn't work with custom IIdentity and IPrincipal on server