Asp.net MVC universal login verification module, asp. netmvc

Source: Internet
Author: User

Asp.net MVC universal login verification module, asp. netmvc

Usage:

I still hope that readers can understand the source code and use it freely. The point is, why is there a UserType !!!

Login User information:

Namespace MVCCommonAuth {[Serializable] public class LoginUser {private const string incluey = "12345678"; 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 = C OokieNamePrefix + userType; var json = JsonConvert. serializeObject (this); var value = EncryptString (json, encryption ey); 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> /// 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 }}

Action verification filter:

Namespace MVCCommonAuth {[AttributeUsage (AttributeTargets. class | AttributeTargets. method, Inherited = true, AllowMultiple = false)] public class AuthFilterAttribute: ActionFilterAttribute {public AuthFilterAttribute () {} public AuthFilterAttribute (string roles, string userType) {this. roles = roles; this. userType = userType;} public bool Allowanonymous {get; set;} public string Roles {get; s Et;} public string Users {get; set;} public string UserType {get; set;} public sealed override void OnActionExecuting (ActionExecutingContext filterContext) {if (Allowanonymous) return; if (IsAuth () return; UnauthorizedRequest (filterContext);} public sealed override void OnActionExecuted (ActionExecutedContext filterContext) {base. onActionExecuted (filterContext);} public sealed override vo Id OnResultExecuting (ResultExecutingContext filterContext) {base. onResultExecuting (filterContext);} public sealed override void OnResultExecuted (ResultExecutedContext filterContext) {base. onResultExecuted (filterContext);} private bool IsAuth () {var user = LoginUser. getUser (UserType); if (user! = Null) {return AuthorizeCore (user. userName, user. roles);} else {return false;} private void UnauthorizedRequest (ActionExecutingContext filterContext) {if (filterContext. httpContext. request. isAjaxRequest () UnauthorizedAjaxRequest (filterContext); else UnauthorizedGenericRequest (filterContext);} protected virtual bool AuthorizeCore (string userName, string userRoles) {var separator = new cha R [] {','}; var options = StringSplitOptions. RemoveEmptyEntries; if (! String. IsNullOrWhiteSpace (Users) {return Users. Split (separator, options). Contains (userName);} if (! String. isNullOrWhiteSpace (Roles) {var allowRoles = Roles. split (separator, options); var hasRoles = userRoles. split (separator, options); foreach (var role in hasRoles) {if (allowRoles. contains (role) {return true;} return false;} return true;} protected virtual void UnauthorizedGenericRequest (ActionExecutingContext filterContext) {// jump to filterContext Based on Roles, Users, and UserType information. result = new R EdirectResult ("/Account/login? Returnurl = "+ filterContext. httpContext. request. url. pathAndQuery);} protected virtual void UnauthorizedAjaxRequest (ActionExecutingContext filterContext) {var acceptTypes = filterContext. httpContext. request. acceptTypes; if (acceptTypes. contains ("*/*") | acceptTypes. contains ("application/json") {filterContext. result = new JsonResult {Data = new {code = 0, msg = "nologin"}, JsonRequestBehavior = JsonRequestBehavior. allowGet };} else {filterContext. result = new ContentResult {Content = "nologin "};}}}}

 

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.