你在這裏。當您使用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;
}
}
烏爾答案可以幫助我... u能請我需要寫什麼代碼來讀取驗證Cookie的身份驗證後的內容。 FormsAuthentication.SetAuthCookie(userName,createPersistentCookie); SetAuthCookie創建一個身份驗證cookie,我需要從服務器端寫入該cookie的內容?請你幫忙。日Thnx。 :) – Thomas
我們可以使用jquery從客戶端創建表單身份驗證Cookie嗎? – Thomas
我已更新以顯示您還可以如何閱讀cookie。不,您不能從客戶端進行設置,因爲這會帶來安全風險,您將無法執行需要服務器端密鑰的加密。 auth cookie應該始終是HttpOnly。唯一的辦法就是創建一個AJAX請求並讓cookie設置爲服務器端,在這種情況下,您需要確保您通過SSL傳遞任何憑據。 – TheCodeKing