Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend or override BeginForm to include a AntiForgeryToken field

I was reading this article (http://weblogs.asp.net/dixin/archive/2010/05/22/anti-forgery-request-recipes-for-asp-net-mvc-and-ajax.aspx) about how to prevent CSRF attacks. It seems like the solution is to create a tag inside each form.

<%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%>

However, I really don't want to copy and paste that code inside of each form. I would like to extend or override the BeginForm to create a BeginSecureForm that automatically adds the AntiForgeryToken. I am not sure how to add content inbetween of the BeginForm and EndForm.

Any ideas?

like image 852
zgirod Avatar asked Jul 01 '11 20:07

zgirod


People also ask

What is the use of HTML AntiForgeryToken () in MVC?

AntiForgeryToken()Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.

What is AntiForgeryToken in web API?

Adding an AntiForgeryToken generates a Cryptographically valid hash at the server end which is split and a part is added as a hidden field, whereas the rest goes into a cookie. When data is posted, the Cookie and the Hidden Field are both sent back and if they are missing or they don't match, the POST is rejected.

How do I disable AntiForgeryToken?

Anti-forgery token validation is enabled by default in Razor Pages. You can disable validation either globally or on individual pages by using [IgnoreAntiforgeryToken] . You can prevent forms from creating anti-forgery tokens by using asp-antiforgery="false" in the form tag helper.


1 Answers

You should use this instead, to place the token at the right place, after the form :

public static MvcForm BeginAntiForgeryForm(this HtmlHelper htmlHelper)
    {
        var mvcForm = htmlHelper.BeginForm();
        htmlHelper.ViewContext.Writer.Write(htmlHelper.AntiForgeryToken().ToHtmlString());
        return mvcForm;
    }
like image 149
mgc Avatar answered Sep 30 '22 09:09

mgc