2011-01-31 113 views
9

我正在使用ASP.NET窗體身份驗證將用戶登錄到我們正在開發的網站中。在ASP.NET中記住我的功能表單身份驗證不起作用

功能的一部分是「記住我」複選框,如果用戶檢查它,它會記住用戶一個月。

在如下記錄的用戶代碼:

public static void Login(HttpResponse response, string username, 
    bool rememberMeChecked) 
{ 
    FormsAuthentication.Initialize(); 
    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now, 
    DateTime.Now.AddMinutes(30), rememberMeChecked, 
    FormsAuthentication.FormsCookiePath); 
    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt)); 
    ck.Path = FormsAuthentication.FormsCookiePath; 

    if (rememberMe) 
    ck.Expires = DateTime.Now.AddMonths(1); 

    response.Cookies.Add(ck); 
} 

在web.config中的相關部分是這樣的:

<authentication mode="Forms"> 
    <forms loginUrl="Home.aspx" defaultUrl="~/" slidingExpiration="true" timeout="43200" /> 
</authentication> 

此記錄用戶不錯,但之後它們記錄瞭如果他們不使用該站點,則需要半小時,但其持久性屬性(rememberMeChecked)設置爲true,如果該屬性爲true,則Cookie設置爲在一個月後過期。有什麼我在這裏失蹤?

由於提前, ˚F

+1

我不確定這是否會在這個實例中有所不同,但是,使用`FormsAuthentication.RedirectFromLoginPage(userName,rememberMe)`有什麼問題?是否需要手動創建票證?如果你在配置中指定了超時時間,那麼你不需要用代碼AFAIK來手工製作它。另外,「rememberMe」的設置在哪裏? – 2011-01-31 13:21:13

回答

0

在我看來,你正在檢查「與rememberMe」,而不是你通過所謂的「rememberMeChecked」變量。

1

嘗試設置表單標籤的Name屬性在你的web.config

此外,Firecookie是再次調試此類問題

只需通過您的代碼閱讀真棒,你還指定DateTime.Now.AddMinutes(30)在您的票證構造函數中...必須檢查它是否會影響它

+0

`name`鏈接已損壞。 – 2013-03-21 00:48:29

+1

@TravisJ更新:) – davidsleeps 2013-03-21 03:45:42

0

您已在構造函數FormsAuthenticationTicket中指定DateTime.Now.AddMinutes(30)。這就是設置登錄的到期時間。

6

看起來您的身份驗證票據仍然配置爲在半小時後過期,即使Cookie本身在30天內過期。您可能還必須延長機票的使用壽命:

public static void Login(HttpResponse response, string username, 
    bool rememberMeChecked) 
{ 
    DateTime expiration = DateTime.Now.AddMinutes(30); 
    if (rememberMe) { 
     expiration = DateTime.Now.AddMonths(1); 
    } 

    FormsAuthentication.Initialize(); 
    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, 
     DateTime.Now, expiration, rememberMeChecked, 
     FormsAuthentication.FormsCookiePath); 

    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(tkt)); 
    ck.Path = FormsAuthentication.FormsCookiePath; 
    response.Cookies.Add(ck); 
} 
-1

我意識到身份驗證票必須更新,而不僅僅是讀取。我的Application_BeginRequest方法現在看起來像這樣:

if (!Request.IsAuthenticated) 
    { 
    HttpCookie ck = Request.Cookies[FormsAuthentication.FormsCookieName]; 

    if (ck != null) 
    { 
     FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(ck.Value); 
     UserManagementUtils.RenewFormsAuthenticationTicket(Response, oldTicket); 
    } 
    } 

這似乎已經照顧它了。