[ASP.NET] 寫入 Authentication Cookie 的 FormsAuthenticationTicket.UserData

[ASP.NET] 寫入 Authentication Cookie 的 FormsAuthenticationTicket.UserData

使用 FormsAuthenticationTicket.UserData 卡關,筆記一下…

當我們需要把特定的資料丟到 Cookie,可以利用 FormsAuthenticationTicket 來存放,不過,它會用到 web.config  的 machineKey ,FormsAuthentication 的加解密會需要用到 machineKey ,請參考:

http://support.microsoft.com/kb/910443/zh-tw

 

倘若你需要用到跨子網域,可以將每一個應用程式的 machineKey 弄成一樣,請參考:

http://www.codeproject.com/Articles/27576/Single-Sign-on-in-ASP-NET-and-Other-Platforms

 

我們可以自己創立 FormsAuthenticationTicket,然後寫入 Authentication Cookie

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1,
    userName,
    DateTime.Now,
    DateTime.Now.AddMinutes(20),
    false,
    userData,
    FormsAuthentication.FormsCookiePath);

var encryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
cookie.HttpOnly = true;
this.Response.AppendCookie(cookie);

 

或者是將 Authentication Cookie 拿出來處理再塞回去
FormsAuthentication.SetAuthCookie(userName, false);
HttpCookie cookie = this.Request.Cookies[FormsAuthentication.FormsCookieName];
//get authen coolie
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
    oldTicket.Version + 1,
    oldTicket.Name,
    oldTicket.IssueDate,
    oldTicket.Expiration,
    oldTicket.IsPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);

var encryptTicket = FormsAuthentication.Encrypt(newTicket);
cookie.Value = encryptTicket;
cookie.Expires = DateTime.Now.AddDays(1);
this.Response.AppendCookie(cookie);

Note:
取出 Authentication Cookie 的方法 FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value);
取出 FormsAuthenticationTicket 的方法 FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value); 

內容出自:http://www.dotblogs.com.tw/yc421206/archive/2013/12/13/133999.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo