ASP.NET MVC Cookie 身份验证
2015-08-03 16:57 Spring.Guo 阅读(3935) 评论(0) 编辑 收藏 举报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(); }
网上身份验证代码很多,参考后做的一个笔记,需要使用时,根据情况修改使用。