What is AntiForgeryToken?

21

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

    
asked by henriquedpereira 09.09.2015 в 20:20
source

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.

    
answered by 09.09.2015 / 20:26
source
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) {
    }
});
    
answered by 31.08.2016 в 16:50