ionic3django-rest-authangular4-httpclient

HttpClient Header could not append Authorization


I am trying to authenticate to a Django Rest API by appending a Token to the Http Header. I already configured the server to allow Cross-Origin Resource Sharing and was able to authenticate previously using the older version of HTTP. The problem started after I upgraded to the latest Ionic CLI (Ionic 3) and started using HttpClient module instead.

Here is a segment of my code:

// get token data from storage
this.storage.get('auth').then((val) => {
this.headers = new Headers();
this.headers.append('Content-Type','application/x-www-form-urlencoded');
this.headers.append('Authorization', val);
console.log(this.headers.get('Authorization')) //displays: Token randomKey1244556etc 


//request
 this.http.get<any>("http://192.168.22.5/api-get-user", {headers: this.headers})
        .subscribe(data => {
            console.log(data);
        }, (err) => {
          console.log(err);
        });
    }, (err) => {
      this.flag = false;
    })

The API returns the following error: {"detail":"Authentication credentials were not provided."}

Here is the detail of the network request sent and the server response:

enter image description here

However, the authentication succeeded when using PostMan using the same credentials appended to the HttpClient Header.

enter image description here

It seems that either the header was not sent with the request or the authorization was not appended to the header. Any idea how to solve the problem?

Note: I am also using CORS Google Chrome extension.


Solution

  • As expected, there is something wrong with the Header. I have solved the problem by customizing the request header by replacing the old header:

    this.headers = new Headers();
    this.headers.append('Content-Type','application/x-www-form-urlencoded');
    this.headers.append('Authorization', val);
    

    to:

    const headers = new HttpHeaders().set('Authorization', val);
    

    Reference: Customizing Http Request Header