1. Create a new class, set the role:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Http.Controllers;usingSYSTEM.WEB.MVC;usingSystem.Web.Security;namespacesoft.dataprovider{ Public enumesoftroles {Admin, User} Public classEsoftroleshelper { Public Static stringGetValue (esoftroles role) {stringRoletype ="User"; if(Role = =esoftroles.admin) {Roletype="Admin"; } Else{Roletype="User"; } returnRoletype; } } Public classEsoftrolesattribute:authorizeattribute {//overloading this method, simulating a custom role authorization mechanism protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {//Obtain the current authentication cookieHttpCookie Authcookie =Httpcontext.request.cookies[formsauthentication.formscookiename]; if(Authcookie = =NULL|| Authcookie.value = ="") { return false; } FormsAuthenticationTicket AuthTicket; Try { //decryption of the current cookieAuthTicket =Formsauthentication.decrypt (Authcookie.value); } Catch { return false; } if(AuthTicket! =NULL) { //is related to the delimiter at the time of deposit, where the delimiter is comma varUserroles = AuthTicket.UserData.Split (New[] {',' }). ToList (); varroles = Roles.split (New[] {',' }). ToList (); returnRoles. Any (x =userroles.contains (x)); } return false; }//skip to page when no permissions protected Override voidhandleunauthorizedrequest (AuthorizationContext filtercontext) {Filtercontext.result=NewRedirectresult ("/account/myauth"); ; } } }
2. Login code:
stringroles =Esoftroleshelper.getvalue (esoftroles.admin); FormsAuthenticationTicket AuthTicket=NewFormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddMinutes ( -),false, roles);//Write User Role stringEncryptedticket = Formsauthentication.encrypt (AuthTicket);//Encrypt the AuthTicketSessioncookiehelper.setcookie ( This. Admincookiename, Encryptedticket, DateTime.Now.AddHours (2)); Info. Countoflogin+=1; Info. Lastlogindate=DateTime.Now; Entity. Configuration.validateonsaveenabled=false; Entity. SaveChanges (); Entity. Configuration.validateonsaveenabled=true;
3. Exit Code:
formsauthentication.signout (); Sessioncookiehelper.clearcookie (this. Admincookiename);
4. Action or controller add:
[Esoftrolesattribute (Roles = "Admin")]
If anonymous access is allowed, add:
[AllowAnonymous]
mvc-logging in and setting up roles