客户端Cookie用户数据验证
前言
IIS发布网站针对客户端用户身份认证采用Cookie核心技术的总结
登录获得加密令牌
/// <summary> /// 获得加密令牌 /// </summary> /// <returns></returns> public static string EncryptToken<T>(T userData, int expireMinutes) where T : class { string strUserData = XmlUtil.ToXml(userData); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "HYFormsToken", DateTime.Now, DateTime.Now.AddMinutes(expireMinutes), true, strUserData); return FormsAuthentication.Encrypt(ticket); }
Web.Config配置增加authentication属性
<system.web> <authentication mode="Forms" /> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" maxRequestLength="40960" /> <sessionState timeout="120"></sessionState> <globalization culture="zh-CN" fileEncoding="utf-8" responseHeaderEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="zh-CN" /> </system.web>
写入客户端Cookie
/// <summary> /// 登录 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="userData"></param> /// <param name="expireMinutes"></param> /// <returns></returns> public static string DoLogin<T>(T userData, int expireMinutes) where T : class { string token = EncryptToken(userData, expireMinutes); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName); cookie.Path = "/"; cookie.Expires = DateTime.Now.AddMinutes(expireMinutes); cookie.Value = token; HttpContext.Current.Response.Cookies.Add(cookie); return token; }
通用XML方法
将验证用户对象统计XML序列化进行封装
/// <summary> /// 将对象序列化为XML字符串 /// </summary> /// <param name="obj">对象</param> /// <returns>对象的xml字符串</returns> public static string ToXml(object obj) { if (obj == null) { return null; } string xml; using (var stream = new MemoryStream()) { var ser = new XmlSerializer(obj.GetType()); ser.Serialize(stream, obj); var len = (int)stream.Position; var bufuer = stream.GetBuffer(); xml = Encoding.UTF8.GetString(bufuer, 0, len); } return xml; } /// <summary> /// 从XML字符串反序列化类 /// </summary> /// <typeparam name="T">目标类型</typeparam> /// <param name="xmlStr">对象的xml字符串</param> /// <returns>类型对象</returns> public static T FromXml<T>(string xmlStr) { Type type = typeof(T); return (T)new XmlSerializer(type).Deserialize(new StringReader(xmlStr)); }
登出时清除Cookie令牌
/// <summary> /// 登出 /// </summary> /// <returns></returns> public static bool Abandon() { FormsAuthentication.SignOut(); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName); cookie.Value = null; HttpContext.Current.Response.Cookies.Add(cookie); return true; }
本文来自博客园,作者:念冬的叶子,转载请注明原文链接:https://www.cnblogs.com/fqzhong2007/p/11045277.html