c#通用登錄模塊分享。本站提示廣大學習愛好者:(c#通用登錄模塊分享)文章只能為提供參考,不一定能成為您想要的結果。以下是c#通用登錄模塊分享正文
// 舉個例子:一個網站有效戶體系、商家體系、網站後台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
再來分享一個示例
1.HTML部門:
<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="" > <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
/*! * 插件稱號:登錄插件封裝,應用辦法: $('#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.頁面挪用插件:
<script type="text/javascript"> $('#form1').login({ url: "AjaxLogin.aspx", userName: $("input[name='userName']"), password: $("input[name='password']"), msg: $(".msg"), button: $("#btnSumit") }); </script>
4.後台處置邏輯(請依據現實需求做響應調劑)
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'}"; //辦事器忙碌,請稍後再試 } } } }