时间:2021-05-20
// 举个例子:一个网站有用户系统、商家系统、网站后台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){}// 用户IDint userID=LoginUser.GetUserID("Administrator")//获取用户名string userName= LoginUser.GetUser("Administrator").UserName再来分享一个示例
1.HTML部分:
2.引入登录插件:login.js
3.页面调用插件:
4.后台处理逻辑(请根据实际需求做相应调整)
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了C#实现简单的Login窗口。分享给大家供大家参考。具体实现方法如下:C#制作登录窗体,登录成功之后正确的做法是关闭(close)登录窗体,而不是
本文实例讲述了C#使用WebClient登录网站并抓取登录后的网页信息实现方法。分享给大家供大家参考,具体如下:C#登录网站实际上就是模拟浏览器提交表单,然后记
本文实例分析了C#中登录窗体和欢迎窗体关闭方法。分享给大家供大家参考。具体分析如下:在c#的winform编程中,我们经常会做登录窗体或欢迎窗体,并把他们作为启
本文实例讲述了C#实现DataSet内数据转化为Excel和Word文件的通用类。分享给大家供大家参考,具体如下:前不久因为项目的需要写的一个C#把DataSe
本文实例讲述了C#操作Access通用类。分享给大家供大家参考。具体如下:usingSystem;usingSystem.Data;usingSystem.Co