1 創建一個ASP.NET MVC 項目
添加一個 AccountController 類。
public class AccountController : Controller { [HttpGet] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] public ActionResult Login(string userName, string password,string returnUrl) { if (CheckLogin(userName, password)) { //加入票據 //保存身份信息 AccountModel ModelUser = new AccountModel() { UserName = userName, Password = password }; string UserData = JsonConvert.SerializeObject(ModelUser);//序列化用戶實體 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddHours(1), false, UserData); HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));//加密身份信息,保存至Cookie Response.Cookies.Add(Cookie); if (string.IsNullOrEmpty(returnUrl)) { return Redirect("~/Home/Index"); } else { return Redirect(returnUrl); } } else { return View("Login", new ResultModel<string>() { Code = 1, Message = "用戶名或密碼錯誤" }); } } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction("Login"); } private bool CheckLogin(string userName, string password) { return MvcApplication.DBList.Any(n => n.UserName == userName && n.Password == password); } }
2 添加一個 自定義attribute ,用來過濾身份登錄
public class CheckLoginAttribute :ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //如果存在身份信息 if (!HttpContext.Current.User.Identity.IsAuthenticated) { ContentResult Content = new ContentResult(); string url = string.Format("{0}?returnUrl={1}", FormsAuthentication.LoginUrl, filterContext.HttpContext.Request.RawUrl); Content.Content = string.Format("<script type='text/javascript'>alert('請先登錄!');window.location.href='{0}';</script>", url); filterContext.Result = Content; } //else //{ // string[] Role = CheckLogin.Instance.GetUser().Roles.Split(',');//獲取所有角色 // if (!Role.Contains(Code))//驗證權限 // { // //驗證不通過 // ContentResult Content = new ContentResult(); // Content.Content = "<script type='text/javascript'>alert('權限驗證不通過!');history.go(-1);</script>"; // filterContext.Result = Content; // } //} } }
3 設置 web.config , 注意 一定要添加 mode=“Forms”
<system.web> .... <authentication mode="Forms"> <forms loginUrl="~/Account/Login" name=".iamshop" ></forms> </authentication> ... </system.web>
4 需要添加權限驗證的地方: 標記一個[CheckLogin] 屬性
[CheckLogin] public ActionResult Index() { //獲取登錄信息 ViewBag.UserName = User.Identity.Name; //獲取對象 // FormsIdentity ticket = (FormsIdentity)User.Identity; HttpCookie authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];//獲取cookie FormsAuthenticationTicket Ticket = FormsAuthentication.Decrypt(authCookie.Value);//解密 // AccountModel account = (AccountModel)JsonConvert.DeserializeObject(Ticket.UserData);//反序列化 AccountModel account= JsonConvert.DeserializeObject<AccountModel>(Ticket.UserData); ViewBag.AccountName = account.UserName; ViewBag.Password = account.Password; return View(); }
網上身份驗證代碼很多,參考后做的一個筆記,需要使用時,根據情況修改使用。