An Introduction to the AntiForgeryToken HTML Helper

The ASP.NET MVC AntiForgeryToken HTML Helper is a widely used but not well-understood helper. In this post, I will look at the details of the helper, explain how it works, and how you should be using it.

 

 

What is the AntiForgeryToken Helper?

The AntiForgeryToken helper protects your site from cross-site request forgery. Cross-site request forgery is the process of submitting data to your site without visiting your site. It can be done programmatically or scripted so that data is sent to your site once or repeatedly and opens you up to several other attacks or exploits.

For example, if an attacker wanted to hide in plain sight, she could create 1000 requests or 10000. It would be harder to find one in so many.

How does it work?

There are two parts to implementing the AntiForgeryToken. The first is on the client. Within the form helper that is being submitted, you will need to use the AntiForgeryToken helper. Its use is very simple:

@Html.AntiForgeryToken()

The AntiForgeryToken helper creates a hidden HTML form field and will generate a ‘token’ string as the field’s value. For example:

<input name="__RequestVerificationToken" type="hidden" value="_xZvPI6jxbLCaXjDU8W0eYLtyhs61Xxeyf1HHSQPlDO7hKL7YUjEBE4IehvvRwTSURknLfgsWM2kiicAbXtTJwDi5OPVm3on-vzkw1W5nzU1">

Also, every request will have a new token.

The second part of the implementation is just as simple to implement. The action result method that is processing the form must be decorated with theĀ [ValidateAntiForgeryToken] attribute.

Now, if requests that are processed by the server that do not come in with the correct __RequestVerificationToken value will be served with the following error message:

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

The value must also be valid. It must be a value that can be decrypted by the server. If you were to try to self-generate the value of the __RequestVerificationToken field, you will be served this error message:

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.

Conclusion

The AntiForgeryToken HTML Helper included in ASP.NET MVC basically gives you a free pass on one of the OWASP Top 10 web application security vulnerabilities and takes only a few seconds to implement for each form.

Leave a Reply

Your email address will not be published.