Read Authorization header from response

匆匆过客 提交于 2020-01-02 08:40:10

问题


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). Chrome Dev tools: console.log of the response headers

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:


2 years too late but hope this helps someone with the same problem:

As @shaochuancs said, the Authorization header is not standard in the response, so the server has to explicitly inform to expose it. To do that the server must add the following header:

Access-Control-Expose-Headers: authorization

Source: https://www.yukei.net/2016/01/getting-response-headers-data-from-an-ajax-request-with-jquery/



来源:https://stackoverflow.com/questions/44032464/read-authorization-header-from-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!