Read Authorization header from response

Viewed 9664

I am working on a side project in which I want to reuse an existing API. The API has an /auth endpoint which handles POST requests and expects the email and password in the request body. If the email and password are verified, then the server returns a response which contains an Authorization header which holds the value for the token which should be sent in all the subsequent requests.

I have a problem retrieving this header from the response. It is visible in both Postman and Chrome Dev Tools (Network section). Postman Chrome Dev tools: XMLHttpRequest console.log of the response headers enter image description here

I have tried multiple libraries/implementations for sending requests (superagent, request, fetch implementation and even XMLHttpRequest), however, all of the responses I get have the Authorization header in the response headers when I look at them in the Chrome Dev Tools, but when I try to access the headers from javascript, I always end up getting the Content-Type header only.

I read in a couple of other answers that the server must specify the Access-Control-Expose-Headers or Access-Control-Allow-Headers with the Authorization value in the headers, however, I do not have access to the server and there are no issues on the API related to this problem, so my guess is that I am missing something when sending the request.

Any ideas?

Here is the request using fetch

return fetch(endpoint, {
    method: 'post',
    body: data,
    headers: {
      [API_KEY_HEADER]: apiKey
    }
  }).then(r => {
    console.log(r);
    console.log(r.headers)
  });

Here is the request using request

r({
    url: endpoint,
    method: 'post',
    headers: {
      [API_KEY_HEADER]: apiKey
    }
  }).then(r => {
    console.log(r);
    console.log(r.headers);
  })

And here is plain old XMLHttpRequest

  const request = new XMLHttpRequest();

  request.open('POST', endpoint);

  request.setRequestHeader('Content-Type', 'application/json');
  request.setRequestHeader(API_KEY_HEADER, apiKey);

  request.onreadystatechange = function () {
    if (this.readyState === 4) {
      console.log('Status:', this.status);
      console.log('Headers:', this.getAllResponseHeaders());
      console.log('Body:', this.responseText);
    }
  };

  const body = {
    'email': 'dummy@test.com',
    'password': 'secret!'
  };

  request.send(JSON.stringify(body));
1 Answers
Related