Home > Back-end >  Adding headers to ajax request fails
Adding headers to ajax request fails

Time:03-25

This would seem to be very straightforward, but I cannot get additional HTTP headers added into a request that I'm attempting to make. I've watched via the browser developer tools as well as with BurpSuite. I'm using JSONP since this is a cross-site call, but that shouldn't matter. I'm stumped and looking for some guidance.

I need to add a token/value in the header of the request I'm making of from a 3rd parties Rest API for authentication. I've stripped the code out into a sample page for debugging purposes. Here is the sample that I'm using:

<!DOCTYPE html>
<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    function getData() {
      $.ajax({
        type: "GET",
        url: "https://<somesite>.com/<path>",
        accept: "application/json",
        dataType: "jsonp",
        crossDomain: true,
        beforeSend: function (xhr) { 
          xhr.setRequestHeader("Accept", "application/json");
          xhr.setRequestHeader("x-token","<token value>"); 
        }, 
        data: {
          select: "timeZoneId"
        },
        success: function (data, status) {
          debugger;
          alert("Sucess");
        },
        error: function (xhr, status, error) {
          debugger;
          alert("Error! :"   xhr.status);
        }
      });
    }
  </script>
  </head>
  <body>
    <button type="button" onclick="getData()">Submit</button>
  </body>
</html> 

I've gone through all kinds of contortions with adding the x-token as a header, but it's never getting added into the request, that I can see. The result of the request is always a 401 unauthorized error, which is the expected error if an invalid/missing x-token is being passed. As I've mentioned, an inspection of the headers does not show the x-token.

The headers that I do see are:

GET /redzone/public/bi/v_completeddataitem?callback=jQuery36009809687059838048_1648150351509&select=timeZoneId&_=1648150351510 HTTP/2
Host: <somesite>.com
Cookie: AWSALBCORS=f 1AWICQyRddSBjj6CNFH6f6XAnVjPOqAMq1JcPj9CCN1x1Izv1cFFXFKo7IKop53Lw4Y95mWWRjzHRAtOwTGccbwbvS8DBCDxJZY8WA9dEwu2Z/XKPeiSV rAsb
Sec-Ch-Ua: "(Not(A:Brand";v="8", "Chromium";v="99"
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36
Sec-Ch-Ua-Platform: "Windows"
Accept: */*
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: script
Referer: http://localhost/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

Thanks in advance for any suggestions.

CodePudding user response:

Don't have the reputation to make a comment... Can you tell us what 3rd party API are you using?

We secure our B2B site with OKTA and make ajax calls like this:

$.ajax({
      url   : api,
      data  : str1,
      headers: {"x-auth-header": localStorage.getItem("access_token")},
      type  : "GET"
})

CodePudding user response:

JSONP works by injecting a <script> element with a src attribute.

There is no way to set request headers on a <script> element.

This is one of the many limitations of JSONP.

Use XMLHttpRequest or fetch to request JSON with CORS instead.


One of the headers you are setting is Accept: application/json which doesn't make sense since the only data format you can parse using JSONP is JSONP (which is a subset of text/javascript).

I have a hunch that the problem is that the third party doesn't support cross-origin requests and you are trying to hack around it by using JSONP. That won't work since JSONP requires they explicitly support JSONP (just as a modern cross-origin request requires that they explicitly support CORS).

If the third-party doesn't support cross-origin requests then you need to make the request from somewhere that is not the browser. e.g. proxy it through your own server.

CodePudding user response:

Did you try just setting the headers property? Note that some headers may fight with what jQuery is trying to do.

$.ajax({
        type: "GET",
        url: "https://<somesite>.com/<path>",
        accept: "application/json",
        dataType: "jsonp",
        crossDomain: true,
        headers: { 
          "Accept": "application/json",
          "x-token": "<token value>" 
        }, 
        data: {
          select: "timeZoneId"
        },
        success: function (data, status) {
          debugger;
          alert("Sucess");
        },
        error: function (xhr, status, error) {
          debugger;
          alert("Error! :"   xhr.status);
        }
      });

  • Related