// 举个例子:一个网站有用户系统、商家系统、网站后台3个系统
//可以分3个userType, user ,shop , system
//网站后台一般都有角色,如admin,employee
//那么网站的角色就有 user,shop,admin,employee,但是admin和employee在一个客户端是不能同时登陆的,所以他们是同一类用户(system)
使用方法:
1、添加一个类LoginUser.cs 代码如下:
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
[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、判断用户是否登录:
1
2
3
4
5
6
7
8
9
10
|
//是否登录 if (LoginUser.GetUserID( "Administrator" ) > 0) { } // 用户ID int userID=LoginUser.GetUserID( "Administrator" ) //获取用户名 string userName= LoginUser.GetUser( "Administrator" ).UserName |
再来分享一个示例
1.HTML部分:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< form id = "form1" runat = "server" > < script src = "../Script/jquery-v1.10.2.js" type = "text/javascript" ></ script > < script src = "login.js" type = "text/javascript" ></ script > < div class = "" style = "height: 160px" > < div > < label for = "userName" > 帐号:</ label > < input type = "text" name = "userName" /> </ div > < div > < label for = "password" > 密码:</ label > < input type = "password" name = "password" /> </ div > < input type = "submit" id = "btnSumit" value = "登录" /> < p class = "msg" > </ p > </ div > </ form > |
2.引入登录插件:login.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
/*! * 插件名称:登录插件封装,使用方法: $('#form1').login({ url: "LoginHandler.ashx",//处理登录验证逻辑的Url userName: $("input[name='userName']"),//用户名输入框 password: $("input[name='password']"),//密码输入框 msg: $(".msg"), //提示信息 button: $("#btnSumit") //提交按钮 }); */ ( function ($) { $.fn.login = function (option) { var defaults = { url: '/account/login/' , msg: $( this ).find( '.msg' ), userName: $( this ).find( "input[name='userName']" ), password: $( this ).find( "input[name='password']" ), button: $( this ).find( "#button" ) }; var options = $.extend(defaults, option); var errMsg = { 'inputUserName' : '请输入用户名' , 'inputPassword' : '请填写登录密码' , 'passwordLength' : '密码应在6-32位字符内' , 'noreg' : '此账号未注册' , 'inviladUserName' : '帐号不存在' , 'accountNotMatch' : '账号密码不匹配' , 'userLocked' : '帐号锁定中,暂时无法登录' , 'serverdown' : '服务器繁忙,请稍后再试' }; //提交数据 function submit() { var userNameInput = $.trim(options.userName.val()); var passwordInput = $.trim(options.password.val()); if (userNameInput == '' ) { showMsg( '登录名不能为空' ); options.userName.focus(); return ; } if (passwordInput == '' ) { showMsg( '密码不能为空' ); options.password.focus(); return ; } $.ajax({ type: "POST" , url: options.url, data: "userName=" + userNameInput + "&password=" + passwordInput, success: function (msg) { var result = eval( "[" + msg + "]" )[0]; if (result.status == "ok" ) { //登录成功处理 showMsg( "登录成功...." ); } else { showMsg(errMsg[result.status]); } } }); } //显示错误信息 function showMsg(msg) { options.msg.html(msg); } //绑定按钮事件 options.button.bind( 'click' , function () { submit(); return false ; }); }; })(jQuery); |
3.页面调用插件:
1
2
3
4
5
6
7
8
9
|
<script type= "text/javascript" > $( '#form1' ).login({ url: "AjaxLogin.aspx" , userName: $( "input[name='userName']" ), password: $( "input[name='password']" ), msg: $( ".msg" ), button: $( "#btnSumit" ) }); </script> |
4.后台处理逻辑(请根据实际需求做相应调整)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
using System; using System.Web; using System.Web.UI; namespace Whir.SiteFactory.Website.Admin.Account { public partial class AjaxLogin : Page { protected void Page_Load( object sender, EventArgs e) { string status = ProcessLogin(); Response.Clear(); Response.Write(status); Response.End(); } private string ProcessLogin() { try { string userName = HttpContext.Current.Request.Form[ "userName" ]; string password = HttpContext.Current.Request.Form[ "password" ]; if ( string .IsNullOrEmpty(userName)) { return "{status:'inputUserName'}" ; //请输入用户名 } if ( string .IsNullOrEmpty(password)) { return "{status:'inputPassword'}" ; //请填写登录密码 } if (password.Length < 6 || password.Length > 32) { return "{status:'passwordLength'}" ; //密码应在6-32位字符内 } //var user = UserService.GetUserByName(userName); //if (user == null) //{ // return "{status:'inviladUserName'}"; //帐号不存在 //} //if (user.IsLocked) //{ // return "{status:'userLocked'}"; //帐号锁定中,暂时无法登录 //} //if (user.Password.ToLower() != password.ToMd5().ToLower()) //{ // return "{accountNotMatch:'ok'}"; //账号密码不匹配 //} //其他操作: //写入客户端cookie //登录日志 return "{status:'ok'}" ; //登录成功 } catch (Exception ex) { return "{status:'serverdown'}" ; //服务器繁忙,请稍后再试 } } } } |