基于ASP.MVC票据FormsAuthenticationTicket身份认证
做一个最基础的业务需求用户登录,将此用户的身份发回到客户端的Cookie,之后此用户再访问这个web应用就会连同这个身份Cookie一起发送到服务端。服务端上的授权设置就可以根据不同目录对不同用户的访问授权进行控制了。
1.场景
当用户登录成功将信息写入Cookie添加全局静态变量,跳转至主界面如果用户认证信息失效就重新跳转至登录界面
2.代码
2.1 设置Cookie
/// <summary> /// 登录验证 /// </summary> /// <returns></returns> [HttpPost] [AllowAnonymous] public ActionResult SetCookie(string loginName, string pwd) { AdminLoginInfo admin = new AdminLoginInfo(); admin.LoginName = loginName; admin.Pwd = pwd; //数据放入ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "login", DateTime.Now, DateTime.Now.AddMinutes(60), false, Newtonsoft.Json.JsonConvert.SerializeObject(admin)); //数据加密 string enyTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(ticket.Name, enyTicket); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); return this.Json(new { success = true, msg = "成功" }); }
2.2 控制器基类BaseController
[AuthorizeAdmin] public class BaseController : Controller { protected AdminLoginInfo info = AdminLoginInfo.get(); }
2.3 AuthorizeAdmin自定义权限认证
继承AuthorizeAttribute并且重写
在过程请求授权时调用 处理未能授权的HTTP请求
public class AuthorizeAdmin : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { AdminLoginInfo info = AdminLoginInfo.get(); bool Pass = false; if (info == null) { httpContext.Response.StatusCode = 401; Pass = false; } else { Pass = true; } return Pass; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.Write(filterContext.HttpContext.Response.StatusCode); if (filterContext.HttpContext.Response.StatusCode == 401) { filterContext.Result = new RedirectResult("/Home/Login"); } } }
2.4全局用户登录信息
public class AdminLoginInfo { public static AdminLoginInfo get() { HttpCookie cook = HttpContext.Current.Request.Cookies["login"]; if (cook == null) { return null; } else if (cook.Value == null) { return null; } AdminLoginInfo mode = null; try { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cook.Value); mode = Newtonsoft.Json.JsonConvert.DeserializeObject<AdminLoginInfo>(authTicket.UserData); //经销商模拟登陆 return mode; } catch { return null; } } public string LoginName { get; set; } public string Pwd { get; set; } }