標籤:style blog http color io 2014 for re
使用者身分識別驗證,依賴於 forms 身分識別驗證類:FormsAuthentication,它是一串加密的cookie 來實現對控制器訪問限制和登陸頁面的存取控制。它在瀏覽器端是這樣子的:
需求:我們要實現對使用者中心只有登入的使用者才能訪問,如果沒登入就跳轉到登入頁面,其它頁面都可以訪問:
首先來看登入控制器的代碼:
UserDto user = UserService.GetUserById(Convert.ToInt32(msg.Msg)); //為提供的使用者名稱提供一個身分識別驗證的票據 FormsAuthentication.SetAuthCookie(user.UName, true, FormsAuthentication.FormsCookiePath); //把使用者物件儲存在票據裡 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user.UName, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), false, JsonConvert.SerializeObject(user)); //加密票據 string hashTicket = FormsAuthentication.Encrypt(Ticket); HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); Response.Cookies.Add(userCookie); //被限制要登入的頁面會在url上帶上上一訪問的頁面 if (Request["ReturnUrl"] != null || Request["ReturnUrl"]!="") { return Redirect(HttpUtility.UrlDecode(Request["ReturnUrl"])); }
web.config 的配置,loginUrl為指定的登入頁面
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> <authorization> <deny roles="controler"/> <allow users="*"/> </authorization>
在控制器加入[Authorize]註解,就可以控制使用者的訪問了,
[Authorize] public ActionResult Index() { UserDto user = UserService.GetUserById(1); return View(user); }
當然也可以註解的屬性來控制不同角色和不同使用者的許可權:
[Authorize(Roles = "controler")] public ActionResult Index() { UserDto user = UserService.GetUserById(1); return View(user); } [Authorize(Users = "admin")] public ActionResult Order() { return View(); }
登出操作:清除cookie
//登出 public ActionResult LoginOut() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); }
如果想更詳細的瞭解forms身分識別驗證請 點 http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html
本代碼已更新到 https://code.csdn.net/denghao156/ktnmb_mvc4