2016年12月28日 星期三

[ASP.NET MVC] Cookie與FormsAuthentication表單驗證自動登入

練習筆記...


[寫入Cookie]

寫法一:
HttpCookie cookie = new HttpCookie("UserData");
cookie.Value = JsonConvert.SerializeObject(userData);
cookie.Expires = DateTime.Now.AddDays(1d);

Response.Cookies.Add(cookie);



寫法二:
HttpCookie cookie = new HttpCookie("UserData")
{
       Value = JsonConvert.SerializeObject(userData),
       Expires = DateTime.Now.AddDays(1d),
};
Response.Cookies.Add(cookie); 


[取得Cookie]
HttpCookie authCookie = Request.Cookies["UserData”];


[FormsAuthentication寫入Cookie] 

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
      version: 1,
      name: data.Account,
      issueDate: DateTime.Now,
      expiration: DateTime.Now.AddDays(1),
      isPersistent: false,
      userData: JsonConvert.SerializeObject(userData),
      cookiePath: FormsAuthentication.FormsCookiePath);

var encryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
cookie.Expires = ticket.Expiration;
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);

※ Cookie name 一定要用FormsAuthentication的CookieName => FormsAuthentication.FormsCookieName


[取得FormsAuthentication寫入的Cookie]

HttpCookie cookie = GetCookie(FormsAuthentication.FormsCookieName);



Ref:
1. 寫入 Authentication Cookie 的 FormsAuthenticationTicket.UserData
2. session與cookies與FormsAuthentication自動登入機制
3. ASP.net MVC整合FormsAuthentication表單驗證登入

沒有留言:

張貼留言