FormsAuthentication を使用して認証 Cookie を書き込む場合、生の Cookie 値を復号化して読み取る必要はありません。ビューで使用でき@User.Identity.Name
ます。
public ActionResult AddNewUser(MemberRegisterModel mm)
{
...
FormsAuthentication.SetAuthCookie(mm.UserName, true || false);
...
return Redirect("Index", "Home");
}
Hello, and welcome, <strong>@User.Identity.Name</strong>
SetAuthCookie の内部は次のようになります。
public static void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.Initialize();
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie,
FormsAuthentication.FormsCookiePath);
}
public static void SetAuthCookie(string userName, bool createPersistentCookie,
string strCookiePath)
{
FormsAuthentication.Initialize();
HttpContext current = HttpContext.Current;
if (!current.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
throw new HttpException(System.Web.SR.GetString("Connection_not_secure_creating_secure_cookie"));
bool flag = CookielessHelperClass.UseCookieless(current, false, FormsAuthentication.CookieMode);
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
if (!flag)
{
HttpContext.Current.Response.Cookies.Add(authCookie);
current.CookielessHelper.SetCookieValue('F', (string) null);
}
else
current.CookielessHelper.SetCookieValue('F', authCookie.Value);
}
private static HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath, bool hexEncodedTicket)
{
FormsAuthentication.Initialize();
if (userName == null)
userName = string.Empty;
if (strCookiePath == null || strCookiePath.Length < 1)
strCookiePath = FormsAuthentication.FormsCookiePath;
DateTime utcNow = DateTime.UtcNow;
DateTime expirationUtc = utcNow.AddMinutes((double) FormsAuthentication._Timeout);
FormsAuthenticationTicket ticket = FormsAuthenticationTicket.FromUtc(2, userName, utcNow, expirationUtc, createPersistentCookie, string.Empty, strCookiePath);
string str = FormsAuthentication.Encrypt(ticket, hexEncodedTicket);
if (str == null || str.Length < 1)
throw new HttpException(System.Web.SR.GetString("Unable_to_encrypt_cookie_ticket"));
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);
httpCookie.HttpOnly = true;
httpCookie.Path = strCookiePath;
httpCookie.Secure = FormsAuthentication._RequireSSL;
if (FormsAuthentication._CookieDomain != null)
httpCookie.Domain = FormsAuthentication._CookieDomain;
if (ticket.IsPersistent)
httpCookie.Expires = ticket.Expiration;
return httpCookie;
}
実際には、フォーム認証チケットを作成し、Cookie を暗号化することに注意してください。