Posted by Anuraj on Sunday, February 4, 2018
This post is how to implement anti forgery validation with ASP.NET MVC and Angular. The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect.
First you need to implement ValidateAntiForgeryTokenAttribute in Web API. Here is the implementation.
This attribute will check whether the request contains a cookie as well as a request header. If they are not the same, or either one is missing, the server knows that the post did not come from our own server and that we shouldn’t trust the input, causing an exception to be thrown. You can set this attribute in Global.asax or to specific action methods, in this blog post I am using it for
POST method only.
To enable AntiForgeryToken in client side, I added a
@Html.AntiForgeryToken() element in the
Index.cshtml file. You can do it
_layout.cshtml as well. This will render the token value as hidden field in the view.
Next in the Angular code, you need to read hidden field and send the value as
X-XSRF-Token in the post request.
For reading the
__RequestVerificationToken hidden field, I am using JQuery, since the
@Html.AntiForgeryToken element is not part of
Angular form, I can’t access using Angular DOM manipulation methods. To use JQuery, first you need to install JQuery (
npm install jquery --save) and can be used like this.
And here is the screenshot of client request with header and cookie value.
Happy Programming :)