AngularJS and AntiForgeryToken in ASP.NET MVC

By Brij Mohan

In my previous article, we have implemented form validation including username availability Check with AngularJS. Now we will use ASP.NET MVC’s AntiForgeryToken to prevent Cross-Site Request Forgery (CSRF) Attacks. It generates a hidden form field (anti-forgery token) that is validated when the form is submitted. I see some tutorials, but I want to do in AngularJS way. Lets play with the previous code and add ValidateAntiForgeryToken attribute in SignUp post action in AccountController.

Note: data-ng-model=”antiForgeryToken”: to define modeldata-ng-init=”antiForgeryToken=’@GetAntiForgeryToken()'”: to initialize model value. In AngularJS, ngModel ignores hidden field but the value will be same on the page so use it.

The required anti-forgery cookie “__RequestVerificationToken” is not present.

3. Creating Attribute Class:

We will process the request, extract the tokens from the request header. Then call the AntiForgery.Validate method to validate the tokens. The Validate method throws an exception if the tokens are not valid. We create a custom attribute for this. Right click on Filters folder and add new class “MyValidateAntiForgeryTokenAttribute.cs”

We have seen how to use the power of ASP.NET MVC’s AntiForgeryToken in AngularJS way. It is very useful when we are working in architecture way where we can’t access value of controls in Ajax request directly.