What is AntiForgeryToken?

21

What is AntiForgeryToken and what does it serve in an ASP.Net MVC application?

    
asked by anonymous 09.09.2015 / 20:20

2 answers

23

This is a method which generates and inserts a code in the HTML generated in the view to avoid falsifying the sending of data to the server.

When using this method it inserts something like this:

<input name="__RequestVerificationToken" type="hidden"
    value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />

When the form is submitted with this code it is possible to validate if it was generated by the current session. The ValidateAntiForgeryToken attribute is used to validate on the controller.

It resolves certain types of attacks, such as CSRF , but not all.

    
09.09.2015 / 20:26
4

If you need to pass the information via AJAX with jQuery you can do this: ~

var token = $('input[name="__RequestVerificationToken"]', form).val();

$.ajax({
    url: "/Controller/Action",
    type: "POST",
    data: {
        __RequestVerificationToken: token,
        IdAnuncio: $("#IdAnuncio").val(),
        Quantidade: quantidade,
        ValorCompra: valorCompra.toFixed(2)
    },
    success: function (data, textStatus, xhr) {
    }
});
    
31.08.2016 / 16:50