ASP. net mvc uses filter to implement page verification and authorization

Source: Internet
Author: User

For ASP. net mvc filter (filter description) See: http://www.cnblogs.com/BreatheLee/archive/2012/06/07/2540469.html

Authorization implementation: http://www.cxy.me/doc/4660.htm

 

In ASP. net mvc, how does one implement form authentication and authorized access? At least in ctp3, there is no official solution. Is Form Verification and authorization mechanisms of ASP. NET webform suitable for ASP. net mvc? Bring these questions into our topic today.

In the architecture of ASP. NET webform, we can implement user authentication and authorization through certain configurations. Especially with the support of the membership function of ASP. NET 2.0, You can implement a simpler and reusable user verification system. Web. config allows you to customize the visibility of different user identities on pages or directories, but it is based on physical files and directories. In ASP. in the. net mvc Architecture, each page accessed by a user does not have a fixed physical file on the disk. It uses a combination of controller control data and views to generate HTML code, and then output to the client. How can we reuse the existing form verification authorization mechanism?

In MVC, the request function entry is the corresponding action function of the controller. We can control the request permission before executing the function. After ASP. net mvc preview 2, a mechanism is provided to intercept action AOP. This interface is defined as follows:

public interface IActionFilter { void OnActionExecuting(ActionExecutingContext filterContext);  void OnActionExecuted(ActionExecutedContext filterContext); }

We have two ways to implement interception, one is to implement the Interception Function by defining attribute, in the system. web. the MVC program has an actionfilterattribute abstract class. by rewriting these virtual methods of this abstract class, we can intercept a specific execution process.

In another method, we noticed that the controller class also implements the iactionfilter interface and also provides virtual method definitions for these four functions. In the framework, these interception methods are also called when the action method is called. For details, see the implementation of the controlleractioninvoker class. All action calls are implemented in this class. Therefore, we only need to rewrite the four virtual methods in the Controller to intercept all the actions in the controller.

Here, I also found a role-based MVC permission control solution that has been implemented by foreign friends. Two custom attributes are defined: requiresauthenticationattribute and requiresroleattribute. These two attributes can be used to act on the class and method. They can be used to mark which controllers or actions need to be logged on, or which roles need to be assigned for execution. If a user does not have the permission to access the Controller or action, the user is automatically redirected to the logon page. The following are the definitions of two classes:

/// <summary> /// Checks the User's authentication using FormsAuthentication /// and redirects to the Login Url for the application on fail /// </summary> [RequiresAuthentication] public class RequiresAuthenticationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //redirect if not authenticated if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { //use the current url for the redirect string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath; //send them off to the login page string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; filterContext.HttpContext.Response.Redirect(loginUrl, true); } } } /// <summary> /// Checks the User's role using FormsAuthentication /// and throws and UnauthorizedAccessException if not authorized /// </summary> public class RequiresRoleAttribute : ActionFilterAttribute { public string RoleToCheckFor { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { //redirect if the user is not authenticated if (!String.IsNullOrEmpty(RoleToCheckFor)) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { //use the current url for the redirect string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath; //send them off to the login page string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; filterContext.HttpContext.Response.Redirect(loginUrl, true); } else { bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.RoleToCheckFor); if (!isAuthorized) throw new UnauthorizedAccessException("You are not authorized to view this page"); } } else { throw new InvalidOperationException("No Role Specified"); } } } 

In the two methods described above, we can define a controller base class to control permissions through interception. However, compared with attribute definition, the method is not very good and is not conducive to generalization. However, theoretically, the performance is better than attribute.

So far, no updates have been made to ASP. net mvc. I think there is an official saying about permission control in the official ASP. NET MVC framework. We hope that there will be a more flexible and configurable solution. Maybe controlling access permissions by controlling URLs is also a feasible solution. Will it be integrated into routetable? Let's try again.

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.