Asp. Net MVC permission Control (2): Controller-Level Control

Source: Internet
Author: User

Next article: Asp. Net MVC permission Control (1): Using Authorize Roles for simple implementation

 

In this example, you can use ActionFilterAttribute to intercept permissions because it has many limitations to mark role names directly on the Controller.

First, create three types of tags:

1. Anonymous Access tag (AnonymousAttribute)
2. LoginAllowViewAttribute)
3. PermissionPageAttribute)

 

The most important permission interception is AuthorizeFilter, which includes three steps for verification:

1. Whether the access is anonymous. If the access is anonymous, the access is passed directly;
2. Check whether permission verification is performed by querying the cookies saved during logon;
3. Check whether you have logged on. If you have logged on directly;

/// <Summary> /// permission interception /// </summary> [AttributeUsage (AttributeTargets. class | AttributeTargets. method, AllowMultiple = false)] public class AuthorizeFilter: ActionFilterAttribute {// <summary> // ASP. net mvc framework call. /// </Summary> /// <param name = "filterContext"> </param> public override void OnActionExecuting (ActionExecutingContext filterContext) {// process if (! This. AuthorizeCore (filterContext) {filterContext. RequestContext. HttpContext. Response. Redirect ("~ /Account/Login ");}} /// <summary> //// permission judgment business logic // </summary> /// <param name = "filterContext"> </param> /// <param name = "isViewPage"> whether it is a page </param> // <returns> </returns> protected virtual bool AuthorizeCore (ActionExecutingContext filterContext) {object [] filter; // verify whether the current Action is an anonymous access Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (AnonymousAttribute), true); if (fil Ter. length = 1) {return true;} // verify whether the current Action is a permission control page Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (PermissionPageAttribute), true); if (filter. length = 1) {// obtain the controllerName var controllerName = filterContext. routeData. values ["controller"]. toString (); // obtain the ACTION name var actionName = filterContext. routeData. values ["action"]. toString (); var validateAuthorize = New ValidateAuthorize (); return validateAuthorize. validate (controllerName);} // verify whether the current Action is a logon user Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (loginallowviewattrites), true); if (filter. length = 1) {return HttpContext. current. user. identity. isAuthenticated;} throw new Exception ("user verification error! ");}}

  

The user logs on and saves the user information.

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Login (LoginModel model, string returnUrl) {string UserData = ""; var userName = model. userName; if (userName = "admin") {UserData = "Log";} else if (userName = "in") {UserData = "Infrastructure ";} else if (userName = "fl") {UserData = "FileLibrary";} FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (1, userName, DateTime. now, DateTime. now. addMinutes (20), false, UserData // 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 RedirectToAction ("Index", "Home ");}

  

Download Code: AuthorizationProject.zip

 

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.