// 舉個例子:一個網站有用戶系統、商家系統、網站後臺3個系統 //可以分3個userType, user ,shop , system //網站後臺一般都有角色,如admin,employee //那麼網站的角色就有 user,shop,admin,employee,但是admin和employe ...
// 舉個例子:一個網站有用戶系統、商家系統、網站後臺3個系統
//可以分3個userType, user ,shop , system
//網站後臺一般都有角色,如admin,employee
//那麼網站的角色就有 user,shop,admin,employee,但是admin和employee在一個客戶端是不能同時登陸的,所以他們是同一類用戶(system)
使用方法:
1、添加一個類LoginUser.cs 代碼如下:
代碼:
namespace MVCCommonAuth { #region 功能說明 // 舉個例子:一個網站有用戶系統、商家系統、網站後臺3個系統 //可以分3個userType, user ,shop , system //網站後臺一般都有角色,如admin,employee //那麼網站的角色就有 user,shop,admin,employee,但是admin和employee在一個客戶端是不能同時登陸的,所以他們是同一類用戶(system) #endregion public enum UserType { User, Shop, System } [Serializable] public class LoginUser { private static string DESKEY = DateTime.Now.ToString("1234MMdd"); public int ID { get; set; } public string UserName { get; set; } public string Roles { get; set; } public DateTime Expires { get; set; } public readonly static string CookieNamePrefix = "authcookie"; public void Login(string userType, string domain = null, string path = null) { var keyName = CookieNamePrefix + userType; var json = JsonConvert.SerializeObject(this); var value = EncryptString(json, DESKEY); HttpCookie cookie = new HttpCookie(keyName, value); cookie.Expires = Expires; if (!string.IsNullOrWhiteSpace(domain)) { cookie.Domain = domain; } if (path != null) { cookie.Path = path; } HttpContext.Current.Items[keyName] = this; HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 從cookie讀取用戶信息 /// </summary> /// <param name="cookieName"></param> private static LoginUser BuildUser(string keyName) { var cookie = HttpContext.Current.Request.Cookies[keyName]; if (cookie != null && !string.IsNullOrEmpty(cookie.Value)) { try { var json = DecryptString(cookie.Value, DESKEY); var loginuser = JsonConvert.DeserializeObject<LoginUser>(json); if (loginuser != null) { if (loginuser.Expires >= DateTime.Now) { return loginuser; } } } catch { //do nothing } } return null; } public static LoginUser GetUser(string userType) { var keyName = CookieNamePrefix + userType; if (!HttpContext.Current.Items.Contains(keyName)) { var user = BuildUser(keyName); HttpContext.Current.Items[keyName] = user; return user; } else { return HttpContext.Current.Items[keyName] as LoginUser; } } public static int GetUserID(string userType) { var user = GetUser(userType); if (user != null) return user.ID; return 0; } /// <summary> /// 退出cookie登錄 /// </summary> public static void Logout(string userType) { var keyName = CookieNamePrefix + userType; HttpCookie cookie = new HttpCookie(keyName, string.Empty); cookie.Expires = DateTime.Now.AddMonths(-1); HttpContext.Current.Response.Cookies.Add(cookie); } #region 字元串加密 /// <summary> /// 利用DES加密演算法加密字元串(可解密) /// </summary> /// <param name="plaintext">被加密的字元串</param> /// <param name="key">密鑰(只支持8個位元組的密鑰)</param> /// <returns>加密後的字元串</returns> private static string EncryptString(string plaintext, string key) { //訪問數據加密標準(DES)演算法的加密服務提供程式 (CSP) 版本的包裝對象 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = ASCIIEncoding.ASCII.GetBytes(key); //建立加密對象的密鑰和偏移量 des.IV = ASCIIEncoding.ASCII.GetBytes(key); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 byte[] inputByteArray = Encoding.Default.GetBytes(plaintext);//把字元串放到byte數組中 MemoryStream ms = new MemoryStream();//創建其支持存儲區為記憶體的流 //定義將數據流鏈接到加密轉換的流 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //上面已經完成了把加密後的結果放到記憶體中去 StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } /// <summary> /// 利用DES解密演算法解密密文(可解密) /// </summary> /// <param name="ciphertext">被解密的字元串</param> /// <param name="key">密鑰(只支持8個位元組的密鑰,同前面的加密密鑰相同)</param> /// <returns>返回被解密的字元串</returns> private static string DecryptString(string ciphertext, string key) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[ciphertext.Length / 2]; for (int x = 0; x < ciphertext.Length / 2; x++) { int i = (Convert.ToInt32(ciphertext.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(key); //建立加密對象的密鑰和偏移量,此值重要,不能修改 des.IV = ASCIIEncoding.ASCII.GetBytes(key); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //建立StringBuild對象,createDecrypt使用的是流對象,必須把解密後的文本變成流對象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } catch (Exception) { return "error"; } } #endregion } }
2、登錄處理過程,寫入cookie:
[HttpPost] public ActionResult Login(string username,string userpass) { if (username=="admin" && userpass=="admin") { LoginUser loginuser = new LoginUser(); loginuser.ID = 1; loginuser.UserName = username; loginuser.Roles = "Administrator"; loginuser.Expires = DateTime.Now.AddHours(2); loginuser.Login("Administrator"); return Content("登錄成功"); //return RedirectToAction("Index", "Home"); } return RedirectToAction("Login"); }
3、判斷用戶是否登錄:
//是否登錄 if(LoginUser.GetUserID("Administrator") > 0) { } // 用戶ID int userID=LoginUser.GetUserID("Administrator") //獲取用戶名 string userName= LoginUser.GetUser("Administrator").UserName