C#登錄退出公共方法,登錄身份加密解密驗(yàn)證
功能:
用戶登錄方法 是否記住密碼自動(dòng)登錄
用戶退出方法
using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Security; namespace JsonsTeam.Common { /// <summary> /// 用戶實(shí)用類(lèi),自定義窗體身份驗(yàn)證時(shí)可以使用。 /// </summary> public sealed class UserUtil { /// <summary> /// 用戶登錄方法 /// </summary> /// <param name="username">用戶名</param> /// <param name="roles">用戶角色</param> /// <param name="isPersistent">是否持久cookie</param> public static void Login(string username, string roles, bool isPersistent) { DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // 票據(jù)版本號(hào) username, // 票據(jù)持有者 DateTime.Now, //分配票據(jù)的時(shí)間 dt, // 失效時(shí)間 isPersistent, // 需要用戶的 cookie roles, // 用戶數(shù)據(jù),這里其實(shí)就是用戶的角色 FormsAuthentication.FormsCookiePath);//cookie有效路徑 //使用機(jī)器碼machine key加密cookie,為了安全傳送 string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //加密之后的cookie //將cookie的失效時(shí)間設(shè)置為和票據(jù)tikets的失效時(shí)間一致 HttpCookie u_cookie = new HttpCookie("username", username); if (ticket.IsPersistent) { u_cookie.Expires = ticket.Expiration; cookie.Expires = ticket.Expiration; } //添加cookie到頁(yè)面請(qǐng)求響應(yīng)中 HttpContext.Current.Response.Cookies.Add(cookie); HttpContext.Current.Response.Cookies.Add(u_cookie); } /// <summary> /// 用戶退出方法 /// </summary> public static void Logout() { HttpCookie cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName); HttpContext.Current.Response.Cookies.Add(cookie); } cookie.Expires = DateTime.Now.AddYears(-10); HttpCookie u_cookie = new HttpCookie("username", string.Empty); u_cookie.Expires = DateTime.Now.AddYears(-10); HttpContext.Current.Response.Cookies.Add(u_cookie); } } }
原文鏈接:C#登錄退出公共方法,登錄身份加密解密驗(yàn)證