mvc-logging in and setting up roles

Source: Internet
Author: User

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

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.