For example: A website has the user system, the merchant system, the website Backstage 3 system
Can be divided into 3 usertype, user, shop, system
Web site background generally have roles, such as Admin,employee
Then the role of the site has user,shop,admin,employee, but admin and employee in a client can not log on at the same time, so they are the same type of user (System)
How to use:
1, add a class LoginUser.cs code as follows:
Code:
namespace Mvccommonauth {#region function description//For example: A website has user system, merchant system, website backstage 3 Systems//Can be divided into 3 usertype, user, shop, System//website Taiwan generally has a role, such as Admin,employee//Then the role of the site has user,shop,admin,employee, but admin and employee in a client can not log in at the same time, so they are the same type of user (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>///reads user information from Cookies///</summary>///<param name= "CookieName" ></par am> private static Loginuser Builduser (string keyname) {var cookie = HttpContext.Current.Request.Cookies
[KeyName]; if (cookie!= null &&!string. IsNullOrEmpty (cookies. Value) {try {var json = decryptstring (cookie).
Value, Deskey);
var loginuser = jsonconvert.deserializeobject<loginuser> (JSON); if (Loginuser!= null) {if (loginuser).
Expires >= DateTime.Now) {return loginuser; The 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>///Exit Cookie login///</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 string Encryption///<summary>///uses DES encryption algorithms to encrypt strings (decrypted)///</summary>///<param name= "plaintext" > Encrypted string </param>///<param "key" > key (only 8 words supported) Section key) </param>///<returns> encrypted string </returns> private static string encryptstring (String Plai ntext, string key) {//Access cryptographic service Provider (CSP) version of the Data Encryption Standard (DES) algorithm wrapper object DESCryptoServiceProvider DES = new Descryp
Toserviceprovider (); Des. Key = ASCIIEncoding.ASCII.GetBytes (key); Set the key and offset of the encrypted object DES.IV = ASCIIEncoding.ASCII.GetBytes (key); GetBytes method using Asciiencoding.ascii method byte[] Inputbytearray = Encoding.Default.GetBytes (plaintext);//Put String to byte Group MemoryStream ms = new MemoryStream ();//create its support store for memory stream///define streams that link data streams to cryptographic transformations CryptoStream cs = new CryptoStream (MS, Des.
CreateEncryptor (), cryptostreammode.write); Cs.
Write (Inputbytearray, 0, inputbytearray.length); Cs.
FlushFinalBlock ();
The above has been done to put the encrypted results into memory to StringBuilder ret = new StringBuilder (); foreach (ByteB in Ms. ToArray ()) {ret.
AppendFormat ("{0:x2}", b); Ret.
ToString (); return ret.
ToString (); ///<summary>///use des decryption algorithm decryption text (can decrypt)///</summary>///<param name= "ciphertext" , decrypted string </param>///<param name= "key" > Key (only 8 byte key is supported, same as previous encryption key) </param>///<returns>
Returns the decrypted string </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);
Establishes the key and offset of the cryptographic object, which is important and cannot be modified 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 ();
To establish the Stringbuild object, Createdecrypt uses the stream object, the decrypted text must be converted into a Stream object StringBuilder ret = new StringBuilder (); Return System.Text.Encoding.Default.GetString (Ms.
ToArray ());
catch (Exception) {return "error";
}} #endregion}}
2, login processing process, write cookies:
[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 ("Login succeeded");
Return redirecttoaction ("Index", "Home");
}
Return redirecttoaction ("Login");
3, to determine whether the user login:
Whether to log in
if (Loginuser.getuserid ("Administrator") > 0)
{
}
//user ID
int userid= Loginuser.getuserid ("Administrator")
//Get user name
string username= loginuser.getuser ("Administrator"). UserName
And share an example.
1.HTML section:
<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 ">
account:</label>
<input type=" text "name=" UserName "/>
</div>
<div >
<label for= "password" >
password:</label> <input type= "password"
name= "password"/>
</div>
<input type= "Submit" id= "Btnsumit" value= "Log In"/> <p class=
"MSG" > </p>
</div>
</form>
2. Introduction of Login plugin: login.js
/*! * Plugin Name: Login plugin Package, use method: $ (' #form1 '). Login ({URL: "loginhandler.ashx",//the URL to process login authentication logic userName: $ ("Input[name= ' u
Sername ']),//Username input box Password: $ ("input[name= ' password ')"),//Password input box msg: $ (". Msg"),//hint info
Button: $ ("#btnSumit")//Submit Button}); */function ($) {$.fn.login = function (option) {var defaults = {url: '/account/login/', msg: $ (this ('. 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 ': ' Please enter username ', ' inputpassword ': ' Please fill in login password ', ' passwordlength ': ' Password should be within 6-32 characters ', ' Noreg ': ' This account is not registered ', ' inviladusername ': ' account does not exist ', ' accountnotmatch ': ' Account password mismatch ', ' userlocked ': ' Account lockout,
Temporarily unable to login ', ' serverdown ': ' Server busy, please try again later '}; Submit data function Submit () {var Usernameinput = $.trim (Options.userName.val ());
var passwordinput = $.trim (Options.password.val ());
if (Usernameinput = = "") {showmsg (' login name cannot be empty ');
Options.userName.focus ();
Return
} if (Passwordinput = = "") {showmsg (' Password cannot be empty ');
Options.password.focus ();
Return $.ajax {type: POST, Url:options.url, data: "Username=" + Usernameinput + &passwor
D= "+ Passwordinput, Success:function (msg) {var result = eval (" [+ msg +] ") [0];
if (Result.status = = "OK") {//Login successfully processed SHOWMSG ("Login successful ...");
else {showmsg (errmsg[result.status]);
}
}
});
///Display error message function showmsg (msg) {options.msg.html (msg);
}//Binding button Event Options.button.bind (' click ', function () {submit ();
return false;
});
};
}) (JQuery);
3. Page Invoke plugin:
<script type= "Text/javascript" >
$ (' #form1 '). Login ({
URL: "ajaxlogin.aspx",
userName: $ ("input[ Name= ' UserName '] ",
Password: $ (" input[name= ' password ') "),
msg: $ (". Msg "),
button: $ (" #btnSumit ")
});
</script>
4. Background processing logic (please adjust accordingly according to the actual demand)
Using System;
Using System.Web;
Using System.Web.UI; namespace Whir.SiteFactory.Website.Admin.Account {public partial class Ajaxlogin:page {protected void Page_loa
D (object sender, EventArgs e) {String status = ProcessLogin ();
Response.Clear ();
Response.Write (status);
Response.End (); private String ProcessLogin () {try {string userName = httpcontext.current.request.form[' Us
Ername "];
string password = httpcontext.current.request.form["password"]; if (string. IsNullOrEmpty (UserName)) {return "{status: ' Inputusername '}";//Please enter the username} if (string. IsNullOrEmpty (password)) {return "{status: ' Inputpassword '}";//Please fill in the login password} if (Password.l Ength < 6 | | Password. Length >} {return "{status: ' Passwordlength '}";//password should be in 6-32-bit characters}//var user = user
Service.getuserbyname (UserName); if (user = null)
{//return "{status: ' Inviladusername '}";//account does not exist//}//if (user. islocked)//{//return "{status: ' userlocked '}";//Account lockout, temporarily unable to login//}//if (user. Password.tolower ()!= Password. ToMd5 (). ToLower ())//{//Return "{accountnotmatch: ' OK '}";//Account password mismatch///Other action://write to Client Cookie/Login Log return "{status: ' OK '}";
Login succeeded} catch (Exception ex) {return "{status: ' Serverdown '}";/server busy, please try again later}}} }