How to set Oauth header

I try to set headers with Oauth 'Authorization': 'Bearer XXXXX'.

But, I got an error.

{"_body":"{\"error\":\"Unauthenticated.\"}","status":401,"ok":false,"statusText":"Unauthorized","headers":{"Cache-Control":["no-cache","
            private"],"Content-Type":["application/json"]},"type":2,"url":"http://myurl.local/api/getApi"}
p_headers = new Headers( // Header for POST, PUT, DELETE
  {
    'Content-Type' : 'application/json',
    'Authorization' : this.tokens.data['token_type']+' '+this.tokens.data['access_token']
  });
  p_options = new RequestOptions({ headers: this.p_headers }); // Options headers for POST, PUT, DELETE

  g_headers = new Headers({ // Header for GET
    'Authorization' : this.tokens.data['token_type']+' '+this.tokens.data['access_token']
  });
  g_options = new RequestOptions({ headers: this.g_headers }); // Options headers for GET

getAPI() {
    return new Promise((resolve, reject) => {
      this.http.get(this.url, this.g_options)
      .toPromise()
      .then((response) =>
      {
        console.log('API Response : ', response.json());
        resolve(response.json());
      })
      .catch((error) =>
      {
        console.error('API Error : ', error.status);
        console.error('API Error : ', JSON.stringify(error));
        reject(error.json());
      });
    });
  }

postAPI() {
    let data JSON.stringify({ ... });
    return new Promise((resolve, reject) => {
      this.http.post(this.url, data, this.p_options)
      .toPromise()
      .then((response) =>
      {
        console.log('API Response : ', response.json());
        resolve(response.json());
      })
      .catch((error) =>
      {
        console.error('API Error : ', error.status);
        console.error('API Error : ', JSON.stringify(error));
        reject(error.json());
      });
    });
  }

In API they call with out Authorization is fine.

How to set header for it?

Can you console.log the p_headers variable please and show us the output?

Ahhh. I can solve this problem. That because, When I load API providers (this code was in API providers), this.tokens.data was unset data (this.tokens.data come from tokens providers).

Sure, I got undefined for this.tokens.data['token_type'] and this.tokens.data['access_token']. This is why i got 403 Unauthenticated.. That was my fault.

And I move set headers code to call API function. It will make new headers when i call it.

1 Like

Hi! I am having some difficulties with setting my headers. I have followed some similar steps. But my headers result in the following.

type or paste code here

_headers
:
Map(2)
size
:
(...)
__proto__
:
Map
[[Entries]]
:
Array(2)
0
:
{"content-type" => Array(1)}
key
:
"content-type"
value Array(1)
0: application/x-www-form-urlencoded"
length :
1

Can the issue be related to the fact that the value is an array ?

Can you show your code.