MVC3 Remote Validation and AntiForgeryToken
After reading about XSS attacks I have applied the AntiForgeryToken to my website using th开发者_如何学JAVAe ValidateAntiForgeryTokenWrapperAttribute described in this article:
http://weblogs.asp.net/dixin/archive/2010/05/22/anti-forgery-request-recipes-for-asp-net-mvc-and-ajax.aspx
It seems to work well however I've come across a problem when using Remote Validation in MVC3. I have a ValidationController which contains all of the common validation within my site and if I apply the ValidateAntiForgeryTokenWrapperAttribute to it then the remote validation no longer works and I get an 'A required anti-forgery token was not supplied or was invalid.' exception logged in Elmah. I've tried debugging this and it doesn't even hit the controller action before throwing the exception. I assume this happens because the remote validation doesn't know to pass the AntiForgeryToken to the controller - has anyone else had this problem or knows whether the two are not meant to be used together?
It also made me question whether I should be using the ValidateAntiForgeryTokenWrapperAttribute on every controller or not, any thoughts?
In the remote attribute do as below:
[Remote("MyValidationMethod","MyController", HttpMethod = "POST", AdditionalFields = "__RequestVerificationToken")]
public object MyField { get; set; }
the AdditionalFields property can accept comma separated fields names in the form; the __RequestVerificationToken is the name of the hidden field which contains the AntiForgeryToken.
I haven't used Remote Validation. However I had similar experience with AntiForgeryToken. When I had it applied for all the actions in my controller. Later, I removed it from all the actions and applied to only those actions which were sending data back to database (insert/update/delete).
As it seems you have applied AntiForgeryToken validation attribute to entire controller, it will always create a new token value every time an action is executed and so when response goes back to client for remote validation action the value of token is different than what is on the form which gets submitted later for other actions.
You can remove AntiForgeryToken attribute from the controller and use it with other action apart from remote validation action or wherever you really need it.
//Instead of this
[ValidateAntiForgeryToken]
public class mycontroller
{
//...
}
//Do something like this
public class mycontroller
{
public ActionResult myotheraction ()
{ }
[ValidateAntiForgeryToken]
public ActionResult valdaitionaction ()
{ }
}
精彩评论