ASP MVC and XSRF

  • Security

This post is part of the series 'Vulnerabilities'. Be sure to check out the rest of the blog posts of the series!

ASP MVC provides a simple method to protect against XSRF attacks . Indeed, you just have to add the following line in the form:

@Html.AntiForgeryToken()

And the ValidateAntiForgeryToken attribute in the controller:

[ValidateAntiForgeryToken]
public ActionResult Create(Model model)

This will add a hidden field in the page and a cookie. When submitting the form, ASP.NET MVC will validate the value of them:

<input name="__RequestVerificationToken" type="hidden" value="geGaItAfh7cil98mAt38y3ymsCsINWs1lH9cZY52lSjZ_bCU3vTgmS8IqONXJo6rLqjAI3pnf9IyUu2O9XGS_NsiSCzhbYy3wI4IeEX6WiQ1"/>

__RequestVerificationToken : 5qqXHEEfzDa_Jn7glEmgtOP586KRLlXOSpyznXvkMooZvQjI9fmDtQ9MH07eIt2vQhBcD44lpRLmMbjTFkkh6H081thqTpdfJ6F3VFLJ0Kw1

The problem is that it is easy to forget the attribute. I therefore write a unit test to check that each method using the Post method is decorated with the ValidateAntiForgeryToken attribute:

[TestMethod]
public void PostMethodShouldBeDecoratedWithValidateAntiForgeryAttribute()
{
    var controllers = typeof(MvcApplication /* N'importe quel type dans le projet web */).Assembly.DefinedTypes.Where(t => typeof(ControllerBase).IsAssignableFrom(t));
    foreach (var controller in controllers)
    {
        controller.Methods()
              .ThatReturn<ActionResult>()
              .ThatAreDecoratedWith<HttpPostAttribute>()
              .Should()
              .BeDecoratedWith<ValidateAntiForgeryTokenAttribute>("because all Actions with HttpPost require ValidateAntiForgeryToken");
    }
}

This test uses the FluentAssertions library .

Or if you do not want to use this library

[TestMethod]
public void PostMethodShouldBeDecoratedWithValidateAntiForgeryAttribute()
{
    var controllers = typeof(MvcApplication).Assembly.DefinedTypes.Where(t => typeof(ControllerBase).IsAssignableFrom(t));
    foreach (var controller in controllers)
    {
        foreach (MethodInfo method in controller.GetMethods())
        {
            if (method.GetCustomAttribute<HttpPostAttribute>() != null)
            {
                Assert.IsNotNull(method.GetCustomAttribute<ValidateAntiForgeryTokenAttribute>(), string.Format("Method {0}.{1} should be decorated with ValidateAntiForgeryTokenAttribute.", controller.Name, method.Name));
            }
        }
    }
}

And there you have no more excuses.

Do you have a question or a suggestion about this post? Contact me on Twitter or by email!

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal