配置,配置mode="Forms",其他屬性詳見 MSDN(點我直接查看各authentication屬性) 。
<configuration> <system.web> <authentication mode="Forms"> <forms name="cookiename" loginUrl="/home/login" defaultUrl="/" timeout="30" path = "/"> </forms> </authentication> </system.web> </configuration>
登錄,有兩種方法,二選一即可,兩者效果是一致的,后者可以帶自定義數據(比如可以放用戶角色)。
[AllowAnonymous] [HttpPost] public ActionResult Login(string username,string password) { //方法1,方便快捷 FormsAuthentication.SetAuthCookie(username, false); //方法2,可以帶自定義數據 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), true, "自定義數據","/"); string hashTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); cookie.HttpOnly = true; Response.Cookies.Add(cookie); //重定向至原始請求URL上 string returnUrl = FormsAuthentication.GetRedirectUrl(username, false); if (!string.IsNullOrEmpty(returnUrl)) { Response.Redirect(returnUrl); } return View("Index"); }
登錄信息,在Login()方法中的username可以在HttpContext.User.Identity.Name獲取,而自定義數據則是存在Cookie中的,想要獲取自定義數據則事先需要將cookie里保存的值解密成認證票據, FormsAuthenticationTicket.UserData 屬性便是我們想要的自定義數據。
[Authorize] public ActionResult UserInfo() { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = HttpContext.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { } ViewData["UserName"] = HttpContext.User.Identity.Name; ViewData["UserRole"] = authTicket.UserData; return View(); }
退出登錄,一句SingOut()即可。
[HttpPost] public ActionResult Logout() { FormsAuthentication.SignOut(); return View("Index"); }
一個奇怪的現象,我折騰了一個晚上始終沒能成功登錄(ASP.NET MVC5),總是在 var cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName] 這一步出了問題,總是出現 cookie==null ,而HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value !=null 的現象。最后清了下瀏覽器緩存......問題消失了.......
FormsAuthentication實現比較簡單,無法滿足復雜身份認證業務的需求,這里僅作為我個人的學習記錄、知識儲備目錄。
參考引用
基於FormsAuthentication的用戶、角色身份認證:https://blog.csdn.net/lenovouser/article/details/53197603
Asp.Net MVC 身份驗證-Forms : https://www.cnblogs.com/JoeSnail/p/8250231.html
經典FormsAuthenticationTicket 分析 :https://blog.csdn.net/wdbs_05/article/details/73737725
總結FormsAuthentication的使用 : https://www.cnblogs.com/ShaYeBlog/p/6268206.html
.Net MVC 身份驗證 :https://www.cnblogs.com/wwj1992/p/8196131.html