【问题标题】:IsInRole with custom WebForms authentication for ASP.NET MVC 5IsInRole 与 ASP.NET MVC 5 的自定义 WebForms 身份验证
【发布时间】:2014-05-28 18:26:46
【问题描述】:

我正在尝试在 ASP.NET MVC 5 应用程序中实现自定义表单身份验证,但我以前没有这样做过,需要一些帮助。我没有使用会员提供程序,但已关注(部分)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”类的任何其他方法之前,您必须调用“WebSecurity.InitializeDatabaseConnection”方法'因为我这样做了不使用成员资格提供程序,WebSecurity.InitializeDatabaseConnection 不应该应用(我已经有我的 SQL 用户表等设置)。

所以我试试

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

但不能将 User 强制转换为 CustPrincipal,因此始终返回 null。

我在这里缺少什么?

【问题讨论】:

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


    【解决方案1】:

    我通过在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 2014-10-12
      • 2011-04-22
      相关资源
      最近更新 更多