What is AntiForgeryToken
and what does it serve in an ASP.Net MVC application?
What is AntiForgeryToken
and what does it serve in an ASP.Net MVC application?
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.
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) {
}
});