Ask_SO Ask_SO - 3 months ago 22
C# Question

Anti-CSRF implementation in MVC 3

I would like to implement Anti-CSRF token in Global.asax file of MVC 3.
Is that possible to implement the same in Gloabl.asax file.

Answer Source

Seems what you need is to create a custom filter class which implements IAuthorizationFilter for all POST methods, by checking HttpContext.Request.HttpMethod request:

public class ValidateAntiForgeryTokenEveryPost : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext context)
    {
        if (context.HttpContext.Request.HttpMethod == "POST")
        {
            System.Web.Helpers.AntiForgery.Validate();
        }
    }
}

Then, add the new filter in FilterConfig class:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ValidateAntiForgeryTokenEveryPost());
    }
}

Also ensure that the custom filter has registered in Global.asax code:

protected void Application_Start()
{
    // other settings

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    // other settings
}

By using global filtering given above, all POST method requests are automatically checks for AntiForgeryToken, no matter if @Html.AntiForgeryToken() is not present inside view pages.

References:

Check CRSF token by default in ASP.NET MVC (standard version)

Securing all forms using AntiForgeryToken (attribute-based version)