Zhou Wei
Zhou Wei

Reputation: 51

validate antiforgerytoken failed via jQuery Ajax in ASP.NET Core in subdomain app

I am working on a project that needs to send post via jQuery Ajax in ASP.NET Core.

$.ajax({
            url: _url,
            headers: {
                [tokenheadername]: token
            },
            type: 'POST',
            data: _data,
            success: function (r) { location.reload(); },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                swal('Error', 'Cannot update entry!' + XMLHttpRequest.status, 'error');
            },

        });

The controller action has a [ValidateAntiForgeryToken] attribute,

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Admin,Manager,User")]
    public async Task<IActionResult> UpdateEntry(Guid id,string filepath,string originalfilename, bool isvideo)
    {
       ...
        return Ok();
    }

Below is the Antiforgery setting in startup file:

services.AddAntiforgery(options =>
        {
            options.HeaderName = "__RequestVerificationToken"; 
            options.Cookie.Name = Configuration["domain"];
        });

It works very well on my local development debug environment. However it fails on product. The product app is in a submain. The Error code is 400.

Really appreciate it for any help.

Upvotes: 0

Views: 223

Answers (1)

cbuck12000
cbuck12000

Reputation: 451

I know this is an older post, but maybe try changing your Ajax call to use beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input[name=__RequestVerificationToken]').val()); }. If the __RequestVerificationToken is empty, you may also need to add @Html.AntiForgeryToken() to your View.

If pre .NET6, update your startup.cs file to have services.AddAntiforgery(options => { options.HeaderName = "XSRF-TOKEN"; });. If .NET 6 or later, add this code to the program.cs file.

Note: If you still have an error, maybe use "IIS Express" in Visual Studio when developing. We found subtle differences when executing an application under kestrel. IIS Express may show you the error that you are experiencing on the product release version of code.

Upvotes: 0

Related Questions