Wednesday 11 November 2020

ASP.NET Core + Antiforgery + jQuery Ajax POST + Nginx - 400 Bad Request

This topic has a lot of similar questions but none of them addresses the specific issue I'm facing today.

The affected environment is:

  • ASP.NET Core 3.1 web app (v3.1.9 Runtime)
  • Ubuntu Server v20.04 Focal
  • Nginx web server (v1.18.0) configured as proxy pass for Kestrel

The issue occurs when issuing an Ajax POST using jQuery (other JS frameworks fail as well), which hits 400 - Bad Request due to the Antiforgerytoken not being properly validated.

The issue is not related to the Antiforgery token missing, since it gets properly added to the Ajax call header fields and/or form fields as well in the appropriate way:

@inject IAntiforgery antiforgery 
@{
    var tokenSet = antiforgery.GetAndStoreTokens(Context);
}

[...]

$.ajax({
    headers: {
        "@tokenSet.HeaderName": "@tokenSet.RequestToken"
    },
    data: {
        "@tokenSet.FormFieldName": "@tokenSet.RequestToken"
    },

    [...]

});

The above pattern to set the Antiforgery token is proved to be working fine, to the point that the call gets accepted in development and even in production when accessing Kestrel directly (no 400 error if Nginx is not involved).

As a matter of fact, the problem seems related to this specific Nginx issue:

In the first thread there's also a workaround, which relies upon the following Nginx settings:

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;

Unfortunately, that suggested workaround is not working for me.

Any clue?



from ASP.NET Core + Antiforgery + jQuery Ajax POST + Nginx - 400 Bad Request

No comments:

Post a Comment