提问者:小点点

MVC4自定义表单身份验证-无法将System. Web.HttpContext.Money.User强制转换为Custom主体


我正在.Net MVC4中构建一个网站,并尝试使用CustomPrincipal对象实现我自己的表单身份验证。

这是我的登录方法...

public void Login(string email)
{
    var user = _userManager.GetUserByEmail(email);

    var encryptedCookieContent = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
        false, user.Id + "|" + user.AccountId + "|" + user.RoleId + "|" + user.Role.Name, FormsAuthentication.FormsCookiePath));

    var formsAuthenticationTicketCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookieContent)
    {
        Domain = FormsAuthentication.CookieDomain,
        Path = FormsAuthentication.FormsCookiePath,
        HttpOnly = true,
        Secure = FormsAuthentication.RequireSSL
    };

    HttpContext.Current.Response.Cookies.Add(formsAuthenticationTicketCookie);
}

这是我的自定义主体

public class CustomPrincipal : IPrincipal
{
    public CustomPrincipal(IIdentity identity, int userId, int accountId, string role, int roleId)
    {
        Identity = identity;
        Role = role;
        RoleId = roleId;
        UserId = userId;
        AccountId = accountId;
    }

    public bool IsInRole(string role)
    {
        return Role == role;
    }

    public bool IsInRole(int roleId)
    {
        return RoleId == roleId;
    }

    public IIdentity Identity { get; private set; }

    public string Role { get; private set; }
    public int RoleId { get; private set; }

    public int UserId { get; private set; }
    public int AccountId { get; private set; }
}

我不是在实现Identity的自定义实例,我只是在重用GenericIdentity。在我的Global.asax文件中,我的Application_AuthenticateRequest方法设置如下。。。

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (Request.IsAuthenticated)
    {
        var formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (formsCookie != null)
        {
            var ticket = FormsAuthentication.Decrypt(formsCookie.Value);
            var principal = PrincipalConfig.CreatePrincipal(ticket);
            System.Web.HttpContext.Current.User = Thread.CurrentPrincipal = principal;
        }
    }
}

原理配置.创建主体是将我的自定义主体对象放在一起的方法。这基本上只是填写userData…像这样…

public static CustomPrincipal CreatePrincipal(FormsAuthenticationTicket ticket)
        {
            var userData =  ticket.UserData.Split('|');
            var principal = new CustomPrincipal(new GenericIdentity(ticket.Name), Convert.ToInt32(userData[0]), Convert.ToInt32(userData[1]), userData[3], Convert.ToInt32(userData[2]));
            return principal;
        }

现在,回过头来参考global.asax文件中的Application _ authenticate request,您可以看到我正在获取新创建的CustomPrincipal对象,并将其分配给system . web . httpcontext . current . user。

这样做后,如果我把下面的立即窗口,而仍在Application_AuthenticateRequest方法…

System.Web.HttpContext.Current.User as CustomPrincipal

正如我所期望的那样,我在Custom主体对象中显示了所有数据。

但是,如果我稍后(在其他控制器操作中)试图访问系统。并将其转换为CustomPrincipal,则返回空值。

同样,对于应用程序中的每个请求,我都可以从application_AuthenticateRequest方法内部的FormsAuthenticationcookie中解密FormsAuth验证Ticket,并找到我的所有UserData。因此,看起来cookie是正确创建和读取的。但是,当新的CustomPrincipal被分配给System.Web.HttpContext.Current.User时,从那时到我试图在另一个控制器内再次访问它时,似乎存在某种断开连接的情况。

有人能看出我可能做错了什么吗?

如果我需要澄清什么,请告诉我。

谢谢


共1个答案

匿名用户

我不确定你是否在使用

Request.IsAuthenticated

正确地

的请求。IsAuthenticated属性本质上返回与上下文相同的值。user . identity . is已验证的属性。在您的代码中,它应该总是返回false,因此分配自定义主体的代码将永远不会触发。

您可以通过在控制器方法中设置断点并检查上下文类型来对此进行调试。代码中的当前用户。是广义同一性吗?如果是这样,你的校长从来没有被指派过。