0

我有一个网站,用户可以在其中使用他们的 facebook 帐户或 twitter 进行身份验证:要了解我使用 cookie 的用户:

全球.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            var id = new MyIdentity(authTicket);
            var userData = authTicket.UserData.Split(',');

            id.SocialProviderName = userData[0].Replace("providerslist=", "").Split('|')[0];
            var newUser = new MyPrincipal(id);
            Context.User = newUser;
        }

    }

用户可以链接两个帐户(facebook 和 twitter)。与 twitter 连接,然后单击“帐户链接”,将被重定向以使用她的 facebook 帐户进行身份验证

问题是,当重定向到第二个帐户时,cookie 变为 null 并且

如果(this.HttpContext.Request.IsAuthenticated){...}

返回假

(如果我使用单个帐户连接,则 cookie 有效,没问题)

我的控制器:

……

FormsAuthentication.SetAuthCookie(socialProfile.UserId, true);

ResetFormsCookie(providerName, socialProfile.UserId);

……

由 GUID 生成的 UserId

  public void ResetFormsCookie(string providerName, string userId)
    {
        var authCookie = HttpContext.Current.ApplicationInstance.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null)
        {
            authCookie = FormsAuthentication.GetAuthCookie(userId, true);
        }
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var userData = authTicket.UserData;
        var providerslist = (from c in userData.Split(',') where c.Contains("providerslist=") select c).FirstOrDefault();
        if (string.IsNullOrEmpty(providerslist))
        {
            userData += string.IsNullOrEmpty(userData) ? "providerslist=" + providerName : ",providerslist=" + providerName;
        }
        else
        {
            if (!providerslist.Contains(providerName))
            {
                userData = userData.Replace(providerslist, providerslist + "|" + providerName);
            }
        }
        var newTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate
            , DateTime.Now.AddDays(90) // authTicket.Expiration ToDo: This need to set in the config
        , authTicket.IsPersistent, userData);
        authCookie.Value = FormsAuthentication.Encrypt(newTicket);
        HttpContext.Current.Response.Cookies.Add(authCookie);
    }

我为我的英语道歉

谢谢,

4

0 回答 0