Search code examples
angularhttpcurlangular-httpclient

Angular HttpClient | Equivalent to curl --user (basic authentication)


I'm trying to access an API using Angular's HttpClient.

I have a key: xxyyzz. According to the API's documentation, I can access resources using the following curl:

curl --user 'key:' https://rest.apiname.com

Question: How can I implement this basic authentication using Angulars HttpClient?

I have tried:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic xxyyzz:'
  })
};

this._http.get('https://rest.apiname.com/resource', httpOptions).subscribe(
  data => {
    console.log(data);
  },
  err => {
    console.log(err);
  }
)

This fails with a 401. Accessing the API using curl works without problems.

Any help us much appreciated!


Solution

  • The value of the basic Authorization header needs to be encoded :

    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json',
            'Authorization': 'Basic ' + btoa('xxyyzz:')
        })
    };