October 24, 2014 07:35 by
Peter
Today, I will show you How to Easily Add ASP.NET MVC 5 Anti-Forgery Tokens to any or all Post Requests. One of the newer attacks against web applications is that the cross-site request forgery attack. It’s an attack against modern applications that store a cookie to represent the presently logged in user. The matter has been explained in different websites.
One of the techniques to stop this attack is to add an anti-forgery token using the @Html.AntiForgeryToken extension technique. On the controller side, the action technique defines the [ValidateAntiForgeryToken] attribute. Behind the scenes, the hidden input field for the anti-forgery token is valid by the ASP.NET MVC 5 framework to confirm it’s correct. Whereas there's discussion as to whether or not this approach is required only for the logging in an anonymous posts, or all posts in general, as been up for debate. However the purpose of CSRF is to attack authenticated users.
public class GlobalAntiForgeryTokenAttribute
: FilterAttribute, IAuthorizationFilter
{
public sub OnAuthorization(filterContext As AuthorizationContext)
{
if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
{
AntiForgery.Validate();
}
}
}
On authorization of the request, if the operation may be a POST request, we tend to call the Validate() method on the AntiForgery helper to actually perform the validation. All of our post operations are currently checked for forgery; but, this can fail as a result of we haven’t added our token globally. To do that, we've to create a custom form extension method just like the following:
public static void FormExtensions
{
public static MvcForm BeginDataForm(this HtmlHelper html, string action, string controller, ...)
{
var form = html.BeginForm(action, controller, ...);
//At this point, the form markup is rendered in BeginForm
// we can render the token
//With every form, we render a token, since this
//assumes all forms are posts
html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());
return form;
}
}
If we use our custom helper for all of our forms, then all of our custom forms can have rendered an anti-forgery token. so we don’t have to worry about making it ourselves, saving time and reducing code.