Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core 2.x and jQuery


Microsoft has greatly simplified ASP.NET Core 2.x implementation of the security implementation on out-of-site request spoofing, that is, someone forging the POST / PUT from another location.
By definition, for the GET and TRACE method there is no protection for this scenario.
With a few simple steps you will be able to implement this level of security in your web application.

1 - In the HTML form of your application add:

  • @Html.AntiForgeryToken()


2 - In the class Controller add the attribute:

  • AutoValidateAntiforgeryToken

So all the methods of the class will be under protection.

Optionally you can work individually by adding to each method the attribute:

  • ValidateAntiForgeryToken

Also worth using the attribute:

  • IgnoreAntiforgeryToken


4 - In the jQuery Ajax call:

     beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());  },


5 - In the Startup class (.cs):

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");


So when someone tries to do a POST/PUT on some protected API method, the server itself will reject the request by returning an HTTP 400 error code.


References: 

  • https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1
  • https://owasp.org/images/7/72/OWASP_Top_10-2017_%28en%29.pdf.pdf

Comentários

Postagens mais visitadas deste blog

Selenium + Firefox = The type initializer for 'System.IO.Compression.ZipStorer' threw an exception

Transmissor sem fio bluetooth Tomate MTB-803 e manual

Problema de rolagem de HTML em iframe no iOS