由于表格身份验证Cookie冲突,我的项目在更新表单身份验证会话时遇到问题。
详细说明:
用户登录后,会创建一个表单身份验证cookie(FACookieA),并对其进行身份验证。但是,在更新cookie时,会创建第二个表单auth cookie(FACookieB),并且不会续订FACookieA。在FACookieA中的到期时间之后,用户被重定向到页面请求上的登录页面,即使它在FACookieB中的到期时间之前。
生成的Cookie:
请注意,这两个Cookie名称相同。
FACookieA :
name: FormsAuth
domain: .formsauth.com
请注意“。”由.NET预先附加,“formsauth.com”来自Forms Authentication Ticket部分
FACookieB :
name: FormsAuth
host: a.formsauth.com
请注意,Cookie使用“host”,而非域名,“a.formsauth.com”基于当前请求网址域。
项目网址测试:
a.formsauth.com
的Web.config:
<forms loginUrl="~/Account/Login.aspx" name="FormsAuth"/>
代码
public partial class Account_Login : System.Web.UI.Page
{
protected void LoginButton_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(LoginUser.UserName.Trim(), LoginUser.Password.Trim()))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
"username",
DateTime.Now,
DateTime.Now.AddMinutes(2),
false,
string.Empty
);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Domain = "formsauth.com";
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Remove(cookie.Name);
Response.Cookies.Add(cookie);
Response.Redirect("~/Account/ChangePassword.aspx"); //authenticated area
}else
{
Response.Write("Invalid UserID and Password");
}
}
}
问题:
1)如何生成一个表单auth cookie,以便用户可以续订表单auth session并且不会被注销?
考虑:
1)项目需要支持多种语言,可能的域格式如下:
a.formsauth.com
a.en.formsauth.com
a.us.formsauth.com
和
b.formsauth.com
b.en.formsauth.com
b.us.formsauth.com
因此,我无法以声明方式设置Forms元素的domain属性。由于两组域无法共享cookie,因此允许在一组内共享cookie。这是相同的代码库用于具有不同域的不同应用程序。但是一组域可以共享cookie。
2)默认的内置FormsAuthenticationModule会更新用户会话cookie,这就是我无法控制cookie中域的原因。请注意,FormsAuthenticationTicket用于在登录时创建cookie,如上所示。
有什么想法吗?
答案 0 :(得分:0)
代码的逻辑不是很清楚,不清楚为什么要尝试替换cookie。)
但是我猜测重定向是在新cookie注册之前发生的。
Response.Cookies.Remove(cookie.Name);
在此处添加代码以检查在尝试添加其他
之前是否删除了Cookie Response.Cookies.Add(cookie);
在重定向
之前,在此处添加代码以确保浏览器已注册cookie(?)答案 1 :(得分:0)
您无法使用相同名称混合主机和域Cookie。为了完成这项工作,需要在顶级域中设置所有cookie。
答案 2 :(得分:0)
尝试使用以下代码。我希望这对您有所帮助。
if(Membership.ValidateUser(LoginUser.UserName.Trim(),LoginUser.Password.Trim())) {
int timeout = model.RememberMe ? 525600 : 30;
//DateTime timeout = model.RememberMe ? 525600 : 30;
string userData = JsonConvert.SerializeObject(model);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, login[0].adminUserName, DateTime.Now, DateTime.Now.AddMinutes(525600), false, userData);
string enTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, enTicket);
Response.Cookies.Add(authcookie);
return Response.Redirect("~/Account/ChangePassword.aspx"); //authenticated area
}
else
{
Response.Write("Invalid UserID and Password");
}