我有一个网站,用户可以通过他们的Facebook帐户或Twitter进行身份验证: 要知道我使用cookie的用户:
的Global.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变为空并且
if(this.HttpContext.Request.IsAuthenticated) {...}
返回false
(如果我使用单个帐户连接,则cookie无效)
我的控制器:
...
FormsAuthentication.SetAuthCookie(socialProfile.UserId,true);
ResetFormsCookie(providerName,socialProfile.UserId);
...
UserID由GUID生成
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);
}
我为我的英语道歉
谢谢,