FormsAuthentication.SetAuthCookie不工作在IE9或Chrome

本文关键字:IE9 Chrome 工作 SetAuthCookie FormsAuthentication | 更新日期: 2023-09-27 18:04:48

抱歉,如果这已经被覆盖了,但我要拔我的头发了。我的网站使用表单身份验证,当我在//localhost上测试时工作完美,但当我发布到web时,它在IE9中不起作用。我遵循了教程中概述的所有步骤,但在使用IE9或Chrome FormsAuthentication时。SetAuthCookie永远不会创建cookie。更重要的是,当我使用Firefox时,它可以工作。下面是我网站上的代码。配置和我在c#中的代码。

基本上,我收集用户的用户名和密码,并通过存储过程对我的SQL Server进行身份验证,然后返回一个临时的web密钥,该网站使用该密钥与用户的配置文件进行交互。web密钥存储在FormsAuthentication cookie中,作为我可以检索以验证登录用户的身份。

另外,我知道身份验证cookie从来没有创建过,因为我在页面上有一个asp:loginstatus控件,它永远不会改变。

web . config:

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" 
         protection="All"
         path="/" 
         slidingExpiration="true" 
         timeout="60"  
         cookieless="AutoDetect" />
 </authentication>
 <authorization>
  <deny users="?"/>
  <allow users= "*"/>
 </authorization>

后面的代码:

void LogUserIn(string UserEmail, string Pwd)
{
    conn = new SqlConnection(connstr);
    sql = new SqlCommand("exec usp_AuthLogin @Email, @Pwd", conn);
    sql.Parameters.AddWithValue("@Email", UserEmail);
    sql.Parameters.AddWithValue("@Pwd", Pwd);
    try
    {
        conn.Open();
        reader = sql.ExecuteReader();
        while (reader.Read())
        {
            Result = reader["Result"].ToString();  // value of webkey
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
        conn.Close();
    }
    // if successful log in and create cookie
    if (Result != "Denied")
    {
        FormsAuthentication.SetAuthCookie(Result, true);  // set cookie with webkey from sql server
        LoggedIn = true;
    }
    else
    {
        LoggedIn = false;
    }
}

请帮

FormsAuthentication.SetAuthCookie不工作在IE9或Chrome

我很确定你需要使用用户名作为SetAuthCookie的第一个参数-这就是FormsAuthentication模块如何知道用户是谁。

SetAuthCookie在底层创建一个验证票。你试过制作自己的真票吗?它可以让你存储额外的数据。

说明如下:http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx#Y1368

基本上你可以这样做:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    isPersistent, //true or false
    webkey, //Custom data like your webkey can go here
    FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

这解释了如何回读数据http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.userdata.aspx

FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string webkey = ticket.UserData;

编辑:另外,默认情况下验证cookie是httponly。您可以使用live headers之类的firefox插件来验证它是否已创建。