Original article address: ASP. net mvc: securing your controller actions
Original Author: Rob conery
Address: http://www.cnblogs.com/QLeelulu/archive/2008/04/04/1137580.html
Translator: qleelulu
First of all, I hope you will learn more about ASP. NET MVCArticleOfTagUnified use:Aspnetmvc(I used ASP. NET MVC all the time, huh)
The actionfilterattribute
ASP. net mvc preview 2 introduces a new actionfilterattribute, which allows you to declare "filter attributes" for your action in the controller ". Think about this, in essence, it is like an "onLoad" event-a short sectionCodeRun the command before or after your action.
UseActionfilterattributeIt is very simple. You declare a class and then override one or two methods of the base class:
Here you can see that we have two methods to rewrite:
- Onactionexecuting: Execute before calling the action method (for example, it can be used for identity authentication)
- Onactionexecuted: Executed after the action method is called (for example, logging)
When you create your filter, you may also need to accessFilterexecutingcontext-A very beautiful object that tells you what will happen to the current app:
Even if you are not familiar with attributes, you can declare attributes. When you use attribute, you can set values for the attributes:
You can set the attribute value as follows:
Set "myfilterproperty" to "somesetting". You can use this property in your onactionexcuting method.
Putting it together
What we want to do is to check whether the current user has logged on before calling the action. If the user has not logged on, we will redirect the user to the logon page, and append a URL for the current page that he can return.
Why use a filter instead of Web. config like webforms? The reason is that you cannot accurately lock an action to use forms authentication. Prior to this, Phil discussed this and made a good explanation:
====>>>>>>>
Assume that you have a website and you want to prevent unauthorized users from accessing the admin folder. As a standard site, you can put the following web. config file in the admin folder:
<? XML version = "1.0" ?> < Configuration > < System. Web > < Authorization > < Deny Users = "*" /> </ Authorization > </ System. Web > </ Configuration >
If you try to navigate to the Admin directory, you will get an error that denies access. However, you may use an implementation as followsWebformroutehandler
To map the URL fizzbucket to the Admin directory:
Routetable. routes. Add (NewRoute ("Fizzbucket",NewWebformroutehandler ("~ /Admin/secretpage. aspx"));
Now, secretpage. aspx In the Admin directory is displayed in the request/fizzbucket URL. This may be what you always want. However, this may not achieve the desired effect. (Original:Now, a request for the URL/fizzbucket will display secretpage. aspx In the Admin directory. This might be what you want all along. Then again, it might not be.)
<=
The key points here are:URLs is not mapped to pages and directories.AndThere are more than one way to skin an action (I don't know how to translate, skim ?) -- You can easily use your routes for ing at the underlying layer, and inadvertently open a URL linked to a secure page (original article: you can easily shoot yourself in the foot with your routes, and inadvertantly open up a URL to a secured page ).Building a Secure action is always a better choice.
Pointing out all of these, we can now build our new filter to check the identity authentication-RequiresauthenticationFilter:
/// <Summary> /// Use formsauthentication to check user authentication /// Redirect to the logon page when verification fails /// </Summary> Public Class Requiresauthenticationattribute: actionfilterattribute { Public Override Void Onactionexecuting (filterexecutingcontext 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 );}}}
Using this method is very simple-you just need to append it to the action method you want to be protected by security:
Another useful filter is used to check specific roles:
/// <Summary> /// Use formsauthentication to check the User Role /// If not authorized, an unauthorizedaccessexception exception will be thrown. /// </Summary> Public Class Requiresroleattribute: actionfilterattribute { Public String Roletocheckfor { Get ; Set ;} Public Override Void Onactionexecuting (filterexecutingcontext 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 ");}}}
Note that I passed a string here to check the role:
You can change it to an enumeration, constant, or another one. You can also change it to more behaviors, such as "requiresusercaneditpage", and make sure that the user is "Administrators" or "content editors" in this method ". the point here is determined by you.
PS: Khan, good English food. I don't know how to translate it in several places. Orz ....