2011-07-20 60 views
0

我想在login.aspx上覆蓋用戶身份驗證票證的到期日期。asp.net登錄控制 - 設置用戶身份驗證票證到期日期

此代碼不能正常工作,因爲1分鐘後用戶仍然通過身份驗證。

private int loginExpire = 1; 
protected void Login_LoggedIn(object sender, EventArgs e) 
{ 
    HttpCookie authCookie = Response.Cookies[FormsAuthentication.FormsCookieName]; 
    FormsAuthenticationTicket oldAuthTicket = FormsAuthentication.Decrypt(authCookie.Value); 

    var newAuthTicket = new FormsAuthenticationTicket(
       oldAuthTicket.Version, 
       oldAuthTicket.Name, 
       DateTime.Now, 
       DateTime.Now.Add    
       (TimeSpan.FromMinutes(loginExpire)), 
       oldAuthTicket.IsPersistent,  
       oldAuthTicket.UserData, 
       FormsAuthentication.FormsCookiePath); 



string encryptedTicket = FormsAuthentication.Encrypt(newAuthTicket); 
authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
HttpContext.Current.Response.Cookies.Set(authCookie); 

FormsAuthentication.RedirectFromLoginPage(GetDestinationPage(lgUserLogin.UserName), false); 
} 

的web.config

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="1"   slidingExpiration="true" protection="All"/> 
</authentication> 

回答

1

編輯爲web.config中認證部分的形式的元素:設置超時= 「1」 和slidingExpiration = 「假」 或代替RedirectFromLoginPage方法使用以下代碼:

String returnUrl; 
if (Request.QueryString["ReturnURL"] == null) 
{ 
    returnUrl = "/Default.aspx"; //your default page url 
} 
else 
{ 
    returnUrl = Request.QueryString["ReturnURL"]; 
} 
Response.Redirect(returnUrl); 
+0

我是否在你的情況下處理Login_LoggedIn事件? – Alexandre

+0

是的,但你可以大幅減少它:if(FormsAuthentication.Authenticate(LoginControl.UserName,LoginControl.Password)){FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName,false); } –

+1

您可以將其保留爲true,但在這種情況下,您必須等待更多超時,然後刷新頁面或執行一些消息回發 –