asp.net mvc:mvc page validation and authorization

Source: Internet
Author: User
Tags abstract httpcontext

In asp.net mvc, how do you implement validation and authorization access to forms? At least in CTP3, there is no official solution. Is the asp.net webform form validation and authorization mechanism suitable for use in asp.net mvc? Take these questions and get into our topic today.

Under the framework of ASP.net webform, we can implement user authentication and authorization through a certain configuration. Especially in the support of the membership function of ASP.net 2.0, we can achieve a more concise and reusable user authentication system. The web.config allows you to customize the visibility of different user identities on a page or directory, but it is based on physical files and directories. Under the asp.net MVC architecture, each page accessed by the user does not have a fixed physical file on the disk, and it generates HTML code through a combination of controller control data and views, which is then exported to the client. So how do we use the existing form authentication authorization mechanism?

In MVC, the requested function entry is controller the corresponding action function, and we can control the request permission before the function executes. After ASP.net MVC Preview 2, a mechanism has been provided that allows us to intercept the action's AOP, which is defined as follows:

1:public Interface Iactionfilter

2: {

3:void onactionexecuted (ActionExecutedContext filtercontext);

4:void onactionexecuting (ActionExecutingContext filtercontext);

5:void onresultexecuted (ResultExecutedContext filtercontext);

6:void onresultexecuting (ResultExecutingContext filtercontext);

7:}

We have two ways to intercept, a function that we can use to define attributes to intercept, there is a ActionFilterAttribute abstract class in the SYSTEM.WEB.MVC assembly, and by overriding these virtual methods of this abstract class, We can then intercept the specific execution process.

Alternatively, we note that the Controller class also implements the Iactionfilter interface, and also provides a virtual method definition of the four functions. Inside the frame, call these blocking methods at the same time when the action method is invoked. The concrete can refer to: Controlleractioninvoker the implementation of this class, all action calls are implemented in this class. So we simply rewrite the four virtual methods in the controller, and we can also complete all the action stops on this controller surface.

Here, I also found a foreign friend has achieved a good role-based MVC permission control scheme. Two custom attributes were customized: Requiresauthenticationattribute and Requiresroleattribute. These two attributes can be used for class and method, to mark which controller or action needs to be logged in, or to have which roles to perform. If the user does not have access to the course controller or action permissions, it will automatically be redirected to the login 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 don't authorized to view this page");


}


}


Else


{


throw new InvalidOperationException ("No role Specified");


}


}


}

As described in the two methods, we can also define a controller base class, by blocking to control the permissions. But compared with the definition of attribute, the technique is not very good, and is not conducive to generalization. But in terms of theoretical performance, it would be better than attribute.

So far, asp.net mvc has not updated the message, I think in the official version of the ASP.net MVC framework, permission control issues will have an official claim. Hopefully there will be a more flexible and configurable scenario. Perhaps by controlling the URL to control access rights is also a feasible solution, will not integrate into the routetable inside it? Let's try to stay in the eye.

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.