Search code examples
.net-5antiforgerytoken.net-6.0

ValidateAntiforgeryToken failure


I'm facing problem of AntiforgeryToken verification.

I'm sending data like this:

var data = {
                    __RequestVerificationToken: '@GetAntiXsrfRequestToken()',
                    Id: id,
                    ResolverGID: resolverGID
                };

I'm using fetch method to send POST data

return fetch(fetchURL, JSON.stringify(data))
            .then(async (response) => {
                return response.json();
            })
            .catch(() => {
                return false;
            });

and sent data looks like this:

Id: 98
ResolverGID: "XXXX"
__RequestVerificationToken: "CfDJ8EaAHBfZaBJBuxJJzC77RytBbhcw-gV2E_x0mfFVVhCy0BSmE9L5w5jzIW-7CrY_pCClHed5Ez6D3vuDj5rWWyoKr90MSOu-uBMGUuoF9iIXQ9y4vUjY_sxa5fghGEo-Xcp5KC541aGD407Fz9D9itZMeID5jqRv61IRINTSwJH_2yRvgg-BC1cDAriut22Oyw"

but my method returns error 400: Bad request.

When I use [IgnoreAntiforgeryToken] instead of [ValidateAntiForgeryToken] attribute it works, but with antiforgery token validation it does not work.

When I use the same token function in modal window to send data it's ok, no problem occurs...

can somebody help me?

Thanks


Solution

  • Maybe I have found the solution to this.

    [ValidateAntiForgeryToken] works only when FormData format is sent, so I had to send data like this:

    let data = new FormData();
                    data.append('Id', id);
                    data.append('ResolverGID', resolverGID);
                    data.append('__RequestVerificationToken', '@GetAntiXsrfRequestToken()');
    

    and then it works as expected.