Can't validate Anti-Forgery token,getting error 400

70 Views Asked by At

I want to implement an anti-forgery token in my software.The problem is that i am doing it outside of a form.

here is my program.cs

{
    options.FormFieldName = "AntiforgeryFieldname";
    options.HeaderName = "X-CSRF-TOKEN";
    options.Cookie.Name = "MyAntiForgeryCookie";
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.HttpOnly = false;
}); 


builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

here is my controller

[AutoValidateAntiforgeryToken]
[Route("api/appointment/public")]
[Authorize(Policy = Permissions.Appointments.MakeAppointments)]

and here is my js

   function create(successCallback) {
       let model = {
           client: appointmentClientService.data.client,
           address: appointmentClientService.data.address,
           animals: appointmentAnimalService.animals,
           deposit: vm.deposit
       };

       Object.assign(model, appointmentData);

       // Retrieve anti-forgery token from the cookie
       const antiForgeryCookie = getAntiForgeryCookie('MyAntiForgeryCookie');
       console.log(antiForgeryCookie); 
       // Include anti-forgery token in the request headers
       const headers = {
           'X-CSRF-TOKEN': antiForgeryCookie
       };
       console.log(headers);
       vm.requestPending = true;
       $http({
           method: 'POST',
           url: '/api/appointment/public',
           data: model,
           headers: headers
       })
           .then(function (response) {
               toastr.success('Appointment created.');
               clearWindowUnloadCheck();

               printPaperwork(response.data.ids, function () {
                   successCallback(response.data);
               });
           })
           .catch(function (response) {
               clinichq.helpers.showErrorMessage(response);
               vm.requestPending = false;
           });
   }

   function getAntiForgeryCookie(cookieName) {
       const cookies = document.cookie.split('; ');
       const antiForgeryCookie = cookies.find(row => row.startsWith(`${cookieName}=`));

       if (antiForgeryCookie) {
           return antiForgeryCookie.split('=')[1];
       }

       return null;
   }

enter image description here

the photo is from my headers

and also here is another picture from my cookies enter image description here

In my console logs i see the correct cookie but I don't know how to validated it.

0

There are 0 best solutions below