2011-08-27 17 views
46

使用FormsAuthentication我們這樣寫代碼:如何手動創建身份驗證Cookie而不是默認方法?

if (IsValidUser()) 
{ 
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
     FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie); 
} 
  1. 我如何手動創建一個身份驗證cookie,而不是寫的?

  2. 如何將登錄頁面中的重定向URL存儲在字符串變量中,而不是寫入FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie)

回答

81

你在這裏。當您使用FormsAuthentication中內置的更高級別的方法時,ASP.NET會爲您處理此問題,但在低級別,需要創建身份驗證Cookie。

if (Membership.ValidateUser(username, password)) 
{ 
    // sometimes used to persist user roles 
    string userData = string.Join("|",GetCustomUserRoles()); 

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1,          // ticket version 
    username,        // authenticated username 
    DateTime.Now,       // issueDate 
    DateTime.Now.AddMinutes(30),   // expiryDate 
    isPersistent,       // true to persist across browser sessions 
    userData,        // can be used to store additional user data 
    FormsAuthentication.FormsCookiePath); // the path for the cookie 

    // Encrypt the ticket using the machine key 
    string encryptedTicket = FormsAuthentication.Encrypt(ticket); 

    // Add the cookie to the request to save it 
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
    cookie.HttpOnly = true; 
    Response.Cookies.Add(cookie); 

    // Your redirect logic 
    Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent)); 
} 

我不知道爲什麼你會想在這裏做一些自定義的東西。如果您想更改用戶數據存儲位置的實現以及用戶如何進行身份驗證,則最好創建自定義MembershipProvider。滾動您自己的解決方案並搞亂認證cookie意味着在您的軟件中引入安全漏洞的可能性很高。

我不明白你的第2部分。如果你想讓用戶返回他們試圖訪問的頁面,當他們被反彈登錄時,你只需要調用FormsAuthentication.GetRedirectUrl。如果你不想做任何你想做的事情,如果你願意,可以重定向到存儲在配置中的url。

要閱讀FormsAuthentication餅乾,通常你會在一個HTTP模塊或在Global.asax鉤AuthenticateRequest事件,並設置用戶IPrinciple上下文。

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 
    if(authCookie != null) 
    { 
     //Extract the forms authentication cookie 
     FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 

     // If caching roles in userData field then extract 
     string[] roles = authTicket.UserData.Split(new char[]{'|'}); 

     // Create the IIdentity instance 
     IIdentity id = new FormsIdentity(authTicket); 

     // Create the IPrinciple instance 
     IPrincipal principal = new GenericPrincipal(id, roles); 

     // Set the context user 
     Context.User = principal; 
    } 
} 
+0

烏爾答案可以幫助我... u能請我需要寫什麼代碼來讀取驗證Cookie的身份驗證後的內容。 FormsAuthentication.SetAuthCookie(userName,createPersistentCookie); SetAuthCookie創建一個身份驗證cookie,我需要從服務器端寫入該cookie的內容?請你幫忙。日Thnx。 :) – Thomas

+0

我們可以使用jquery從客戶端創建表單身份驗證Cookie嗎? – Thomas

+3

我已更新以顯示您還可以如何閱讀cookie。不,您不能從客戶端進行設置,因爲這會帶來安全風險,您將無法執行需要服務器端密鑰的加密。 auth cookie應該始終是HttpOnly。唯一的辦法就是創建一個AJAX請求並讓cookie設置爲服務器端,在這種情況下,您需要確保您通過SSL傳遞任何憑據。 – TheCodeKing

-7

創建cookie的其他方式,

HttpCookie toolCookie = new HttpCookie("xyz"); 
toolCookie["UserName"] = userName; 
toolCookie["Password"] = StringCipher.Encrypt(password, "#!"); 
toolCookie.Expires = DateTime.Now.AddMinutes(chkRemember.Checked ? 30 : -30); 
Request.Cookies.Add(toolCookie); 

Reference

獲取現有的Cookie信息

HttpCookie user = Request.Cookies["xyz"]; 
if(user != null) 
{ 
    string username = user["UserName"]; 
    string password = user["Password"] != null ? StringCipher.Decrypt(user["Password"], "#!") 
} 

這裏Datasecurity是一個靜態類。

加密和解密功能Encrypt & Decrypt

+10

切勿將密碼放入cookie中。這失敗了整個安全cookies的點 –

+0

你能否建議我最好的解決方案相同 – Vijayaraghavan

+0

你可以檢查這個例子.. http://www.aspsnippets.com/Articles/Implement-Remember-Me-functionality-using-CheckBox- ASPNet.aspx – Vijayaraghavan