FormsAuthenticationTicket 此功能主要在記錄使用者是否已經登入,實際上
會產生一組 Cookie,內含一組經過加密的編碼,.net 可以透過檢核這組編碼,
來判斷使用者是否已經登入(或者說已獲得允許使用的權限)。
使用者在開啟頁面,程式進入 Action 前,先檢查使用者登入的驗證,也就是指
是否已取得 ticket,若未通過驗證,則跳轉到登錄頁,若已驗證,則允許進入
Action 內。
當使用者已經在登錄頁登錄,且檢核通過,則產生一張 ticket (也就是一組 Cookie),
當使用者切換頁面時,瀏覽器便會再把這組 ticket(Cookie),帶到後端,後端只
要檢核這組 ticket,就可以得知使用者是否仍處於已驗證的狀態。
1.在要進行驗證的 Action 前掛上 [Authorize()]
[Authorize()]
public ActionResult Home2()
{
return View();
}
2.在 WebConfig 中加上,當驗證失敗時要導向的頁面位置(要加在專案下的那個 WebConfig)
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login/Index" cookieless="UseCookies" timeout="2880" />
</authentication>
</system.web>
3.當使用者登入後,寫入一張 ticket,讓之後進入 action 前能通過 [Authorize()] 驗證
public ActionResult Login(string uid)
{
//驗證使用者輸入的帳號密碼
if (uid.ToUpper() == "UID")
{
//驗證通過,建立一張 ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, //票證的版本琥碼
uid, //與票證相關的使用者名稱
DateTime.Now, //核發此票證時的本機日期和時間
DateTime.Now.AddMinutes(60), //票證到期的本機日期和時間
false, //如果票證將存放於持續性Cookie中,則為true
"", //要與票證一同存放的使用者特定資料
FormsAuthentication.FormsCookiePath); //票證存放於Cookie中時的路徑
//ticket 生成 cookie
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
httpCookie.HttpOnly = true;
//cookie 寫入 response
Response.Cookies.Add(httpCookie);
//轉向到首頁
return View("Home");
}
else
{
//驗證不通過,返回到登錄頁
return View("Index");
}
}
沒有留言:
張貼留言