ASP. NET MVC Permissions control (i): simple implementation using authorize Roles

Source: Internet
Author: User

Recently due to the needs of the project to control the rights to do a few demo, stickers out for everyone to shoot bricks!

First create a basecontroller, and let all controllers inherit from the Basecontroller.

    [Authorize]    public class Basecontroller:controller    {    }

System logins require a accountcontroller, inherit from Basecontroller, and add anonymous access token allowanonymous.

AccountController implements the login function of the system and saves the user information in a cookie.

    [allowanonymous] public class Accountcontroller:basecontroller {public ActionResult Index () {        return View ();            } public ActionResult Login (string returnUrl) {viewbag.returnurl = RETURNURL;        return View (); } [HttpPost] [allowanonymous] [Validateantiforgerytoken] public actionresult Login (Loginmodel            Model, String returnUrl) {String roles = ""; var userName = model.            UserName;            if (UserName = = "Admin") {roles = "admin";            } else if (UserName = = "IB") {roles = "ibusiness";            } else if (UserName = = "ia") {roles = "iapproval"; } FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket (1, US Ername, DateTime.Now, DateTime.Now.AddMinutes ((), False, roles//write user role);            String encryptedticket = Formsauthentication.encrypt (AuthTicket);            System.Web.HttpCookie Authcookie = new System.Web.HttpCookie (Formsauthentication.formscookiename, encryptedticket);            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Authcookie); return string.                IsNullOrEmpty (RETURNURL)?        Redirecttoaction ("Index", "Home"): Redirecttolocal (RETURNURL);            } Private ActionResult Redirecttolocal (string returnUrl) {if (Url.islocalurl (RETURNURL))            {return Redirect (RETURNURL);            } else {return redirecttoaction ("Index", "Home");            }} public ActionResult LogOff () {formsauthentication.signout ();        Return redirecttoaction ("Index", "Home"); }    }}

Add a role validation token to the system's business controller.

    [Authorize (Roles = "Admin,ibusiness,iapproval")]    public class Infrastructurecontroller:basecontroller    {public        actionresult Index ()        {            return View ();        }        [Authorize (Roles = "ibusiness")]        Public ActionResult Add ()        {            return View ();        }        [Authorize (Roles = "Iapproval")]        Public ActionResult Approval ()        {            return this. View ();        }    }

  

Finally, add validation in Global.asax.

        <summary>//Construction method///</summary> public mvcapplication () {        AuthorizeRequest + = new EventHandler (application_authenticaterequest); } protected void Application_AuthenticateRequest (Object sender, EventArgs e) {HttpCookie Authcoo            Kie = Context.request.cookies[formsauthentication.formscookiename];            if (Authcookie = = NULL | | authcookie.value = = "") {return;            } FormsAuthenticationTicket AuthTicket = null;            try {AuthTicket = Formsauthentication.decrypt (Authcookie.value);            } catch {return;            } string[] Roles = AuthTicket.UserData.Split (new char[] {', '}); if (Context.User! = null) {Context.User = new System.Security.Principal.GenericPrincipal (Contex            t.user.identity, roles); }        }

  

Code Download: Authorizationpro.zip

(note: Due to too many DLLs, file compression is too large, the demo DLL package has been deleted)

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.