C # General login module, which is simple and easy to use,

Source: Internet
Author: User

C # General login module, which is simple and easy to use,

// For example, a website has three systems: User System, merchant system, and website background.
// Three usertypes, user, shop, and system are allowed.
// The website background usually has roles, such as admin and employee
// The website roles include user, shop, admin, and employee. However, admin and employee cannot log on to the same client at the same time, so they are users of the same type (system)

Usage:

1. Add a class LoginUser. cs Code as follows:

Code:

Namespace MVCCommonAuth {# region function description // For example, a website has three systems: user System, merchant system, and website background. // three usertypes, user, and shop are allowed, system // The website background usually has roles, such as admin and employee. The website roles include user, shop, admin, and employee, however, admin and employee cannot log on to the same client at the same time, so they are users of the same type (system) # endregion public enum UserType {User, Shop, system} [Serializable] public class LoginUser {private static string secret ey = DateTime. now. toString ("1234 MMdd"); public int ID {g Et; 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, encryption ey); HttpCook Ie 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> /// read user information from the 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, secret ey); 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> /// log out of cookie /// </summary> public static void Logout (string userType) {var keyName = CookieNamePrefix + userType; HttpCookie = new HttpCookie (keyName, string. empty); cookie. expires = DateTime. now. addMonths (-1); HttpContext. current. response. cookies. add (cookie) ;}# region string encryption /// <summary> /// use the DES encryption algorithm to encrypt the string (decrypted) /// </summary> /// <param name = "plaintext"> encrypted string </param> /// <param name = "key"> key (only supports 8-byte keys) </param> // <returns> encrypted string </returns> private static string EncryptString (string plaintext, string key) {// Access Data Encryption Standard (DES) DESCryptoServiceProvider des = new DESCryptoServiceProvider (); des. key = ASCIIEncoding. ASCII. getBytes (key); // create the key and offset des of the encryption object. IV = ASCIIEncoding. ASCII. getBytes (key); // use ASCIIEncoding in the original text. the GetBytes method of the ASCII method byte [] inputByteArray = Encoding. default. getBytes (plaintext); // put the string in the byte array MemoryStream MS = new MemoryStream (); // create a stream that supports storage for memory // define the stream that links the data stream to the encrypted conversion CryptoStream cs = new CryptoStream (MS, des. createEncryptor (), CryptoStreamMode. write); cs. write (inputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); // The encrypted result is put in the memory to StringBuilder ret = new StringBuilder (); foreach (byte B in ms. toArray () {ret. appendFormat ("{0: X2}", B);} ret. toString (); return ret. toString () ;}/// <summary> // use the DES decryption algorithm to decrypt the ciphertext (decrypted) /// </summary> /// <param name = "ciphertext"> decrypted string </param> /// <param name = "key"> key (only supports 8-byte keys, same as the preceding 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); // create the key and offset of the encryption object. This value is important and cannot be modified. 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 (); // create a StringBuild object. createDecrypt uses a 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. During the login process, write the 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 ("Logon successful"); // return RedirectToAction ("Index", "Home");} return RedirectToAction ("Login ");}

 

3. Determine whether a user is logged on:

// Whether to log on to if (LoginUser. getUserID ("Administrator")> 0) {}// user IDint userID = LoginUser. getUserID ("Administrator") // obtain the userName string userName = LoginUser. getUser ("Administrator "). userName

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.