Creating a mandatory Anti-Forgery token

One of the things I love about ASP.Net, is that a lot of the hard work that is required for a creating a secure website has already been done for you. It usually only takes a couple of lines of code to add these features in which means there are no excuses for missing off important security measures.

Anti-Forgery Token

One of these features is the Anti-Forgery token and it can be added to your MVC website with just 2 lines of code. So what is an anti-forgery token? As the name suggests it is a token to prevent forgery! In the same way that someone might forge a signature to pretend to be someone else, it is possible for a malicious person to forge a request to your website without the request coming from your website.

So how is this done I hear you say? Well lets say you have a form on your website for changing user details such as name and email address, and a hacker wanted to change these to something else.

The hacker could create a form on another website which matches the request your website is expecting and post to the same URL. The entire form could be in hidden fields and posted via an Ajax request on page load making it invisible to the user.

If the user is already logged in to your website when the other website posts the form, your website treats it as a valid request and will change the user details to whatever the hacker wants.

So how do we get around this?

Well in the same way that 2 factor authentication works on something you know and something you have. The anti-forgery token works as the something you have (sorry about the poor analogy). The server places a hidden field with a populated anti-forgery token into your form. When a request is made to your website, the server checks for the presence of the anti-forgery token and if it doesn’t exist or doesn’t match the expected value an exception occurs.

As the hackers malicious form doesn’t know what the Anti-Forgery token is the request fails.

Adding an Anti-Forgery token

This all sounds great so how do you add this in? As i mentioned you only need 2 lines of code to add in an Anti-Forgery token, one in the view and one in the controller.


In the view you need to add in the anti-forgery token with @Html.AntiForgeryToken()  inside your post form like this:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{      @Html.AntiForgeryToken()


The controller then needs to have the [ValidateAntiForgeryToken] added to the post action.

// POST: /Account/Login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{      if (!ModelState.IsValid)      {            return View(model);      }

If you look at the source code of your page you should now see the following in your form (with a different value of course):

<input name="__RequestVerificationToken" type="hidden" value="JN8mexoJ6sCyfy9TzagXr1DSmjk6au-5VfP9IN_EyLhkWwvd-w2HGJ5EzCW1e_W9nf3wpTQWG_bDgDFFhzLWU8EqAb_8uQtXTwvojSTe3541">

Ok so lets test it by changing the value in this hidden field and seeing what happens.

<input name="__RequestVerificationToken" type="hidden" value="bad token">


As shown above we get the expected exception that the anti-forgery token could not be decrypted. In production you will have custom errors turned on so the user will see a nice error message instead of a stack trace which is dangerous in itself.

Making the Anti-Forgery token mandatory

As you might have guessed from the title of this post, we aren’t finished yet. If you are working in a team it is possible that someone might forget to add the anti-forgery token into their new view and action. So what happens if you forget to add the token to the view?


As you would expect you get an exception saying that the token is missing. Great, but what happens if you forget to add the ValidateAntiForgeryToken to the action?

Nothing. No exception. It just allows it through.

Given that you have to add an attribute to every post action it is conceivable to think one could be missed.

We can mitigate this issue by doing 2 things:
1.) Use an HTML Helper Extension for BeginForm to always add in the token.
2.) Write a unit test to check for the presence of the ValidateAntiForgeryToken on every Post action.

So how do we do this:
1.) Use an HTML Helper extension for BeginForm
To create a HTML Helper extension we are going to create a new class called HtmlExtensions and place it somewhere in our project. You then need to add the following method:

public static MvcForm BeginFormWithToken( this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes)
    var form = htmlHelper.BeginForm(actionName, controllerName, routeValues, method, htmlAttributes);
    return form;

Now I have only created one for the BeginForm method shown above but you will probably want to create one for each of the other overloads you use. You will then need to go through each of your views and change BeginForm to BeginFormWithToken. So now we have the Anti-Forgery token being added to every form.

2.) Write a unit test to check for the presence of the ValidateAntiForgeryToken
To do this we have to use reflection to find all the controller actions with HttpPost and check that they have a ValidateAntiForgeryToken present. In the example below you will need to change MyWebApplication to the name of your Web project.

public void TestValidateAntiForgeryTokenAttributeOnAllPostActions()
    // Act
    var actions = Assembly.Load("MyWebApplication").GetTypes()
						.Where(t => typeof(Controller).IsAssignableFrom(t))SelectMany(type => type.GetMethods()).Where(method => method.IsPublic &&
						method.GetCustomAttributes(typeof(HttpPostAttribute), true).Any() &&
						!method.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true).Any()).ToList();
    // Assert
    Assert.IsFalse(actions.Any(), actions.Any() ? $"The action '{actions[0].Name}' in the '{actions[0].DeclaringType.Name} ' controller is missing the ValidateAntiForgeryToken attribute." : string.Empty);

This test will fail if any of the actions are missing the validate attribute and will give the name of the first offender. Feel free to modify this. For example you might want to get it to print out all of the actions that are missing the Anti-Forgery token attribute.

If this post was helpful please leave a comment below.

Best Adult Coloring Books for Geeks

I think most people have fond memories of colouring from their childhood, there is something about making a black and white picture come to life with colour that is very satisfying. I first heard about adult coloring books about a year ago when looking at forms of meditation. As a child it is called colouring in, as an adult it is called mindfulness. As a software engineer it is good to have a hobby that doesn’t involve looking at a screen.

I started with The Mindfulness Coloring Book, and although it is probably good for some people I didn’t like the mindless random patterns. I think anyone with even a mild case of OCD would find this book frustrating as sometimes the lines don’t match up making alternating patterns impossible.

My wife has a couple of good colouring books such as Millie Marotta’s Animal Kingdom and Johanna Basford’s Enchanted Forest. The problems is I don’t want to colour in flowers, animals or random patterns. My 2 year old daughter loves colouring at the moment and I think it was colouring in with her that made me realise I like using realistic colours.

Continue reading

Why can’t all programming books look like this?

I have read quite a lot of programming books over the years. A lot of them have been really useful in learning a new programming language and some of them have been less than helpful. Unfortunately, the one thing all these books had in common was how dull they were to read. It’s not necessarily the fault of the author, programming is more of a practical subject and reading pages on pages of code can get a bit dry after a while. Some books do try and add a bit of humour to break up the monotony but even this can get a bit annoying after a while (yes, I mean you Head First).

Continue reading

Problems with VirtualBox + Vagrant on Windows 10

I am big fan of Vagrant. I first discovered Vagrant when I was looking for ways of creating a development environment that I could transfer between various computers (I had a desktop and laptop I regularly worked on).  I even toyed with the idea of installing a Linux distro on a fast USB 3 stick to carry round. It was then, while in my search for the perfect development environment that I discovered Vagrant. However I haven’t got Vagrant on Windows 10 working until now.

Vagrant was working fine the last time I used it, mainly for WordPress theme development. I haven’t touched it for about 6 months now but after typing vagrant up and waiting I was soon greeted with this:

Continue reading

Best Practices for a RESTful API

Nowadays the web is powered by APIs. With applications being used on desktop and mobile, APIs are essential in allowing the code in backend systems to be reused. The most popular APIs from companies such as Facebook, Google, and Twitter use the RESTful API pattern.

Unlike other parts of your web site or app, your API should be designed to be used by programmers, like you. If you have ever used a badly designed API you will know how frustrating it can be to try and integrate with it. So what are some things you can do to make a good RESTful API.

Continue reading

The Big List of Free Pluralsight Courses for Developers

The Big List of Free Pluralsight Courses for DevelopersOne of the most important aspects of being a software developer is the ability to learn new skills quickly. Our industry is moving so quickly you have to keep learning new technologies so your skills don’t get old.

There are many great resources online for learning new skills but I have found Pluralsight to have the largest collection of quality videos out there. Most of the courses on Pluralsight are many hours long and made by well known developers such as Scott Allen, Troy Hunt, Scott Hanselman and Jon Skeet.

I should point out this isn’t a promotional post for Pluralsight, I am just happy customer.

What is a little less known about Pluralsight is that there many courses that are free to watch without an account. Here is a list of all the free Pluralsight courses I have found that would be useful for developers.

Continue reading

Analysing Google Play to find a profitable app idea – Part 5: PlayDrone

So far I have used the PlayDrone data to find out what the most downloaded free games, paid games and paid apps are. There are many useful queries that can be run to try and find a profitable app idea. For example, you could look at apps with lots of downloads but with a bad user rating. You could then look at the comments for that app and find out why the users are dissatisfied with it and make a better app! You could even get a list of all paid apps that have made at least £10,000 if you wanted. It could also be useful to look at apps that have failed, by running a query to find apps that have never been downloaded and then find out why, so your apps don’t suffer the same fate.

You can download a 735MB Json (JavaScript Object Notation) file that contains details of the 1.4 million apps on Google Play as of 31/10/2014 from the Internet Archive. I had some fun writing a console app that inserts details about all these apps into SQL, so that queries can be run against it. You can find the source code for this on my GitHub account with the imaginative name of PlayDrone2SQL.

Continue reading

Analysing Google Play to find a profitable app idea – Part 3: Paid games

In my last post I looked at some of the most downloaded freemium games of all time, which are all guaranteed to be making a lot of money. As it turns out the majority of freemium games fall into only a small number of categories.

You can get a lot of information about what works, by looking at the most popular games that have been downloaded. Paid for games, are particularly interesting, as they have managed to overcome the most important hurdle that freemium games face. Getting users to hand over their money! People will only tend to buy something if they know it is going to be good. As result, paid games have much lower download figures compared to freemium games.

So lets have a look at the top 20 paid games on Google Play that have managed to crack open users wallets. As with my previous post, this data comes from the PlayDrone project as the top charts on Google aren’t particularly useful for analysis.

Continue reading