1

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!

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • 1
    pls have a look at this : https://stackoverflow.com/questions/50694913/angular-6-httpclient-passing-basic-auth-in-httpoptions/50696466 – jcuypers Apr 02 '19 at 13:23

2 Answers2

3

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

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

here is How to make request with basic auth

   const basicAuth = username + ':' + password;
    let Headers = new HttpHeaders();
    Headers = Headers.append('Authorization', 'Basic ' + btoa(basicAuth));
    return this.http.post<any>(`${this.authUrl}getLoggedInUserInfo.json`, null, { headers: Headers })
Kenana Reda
  • 430
  • 1
  • 9
  • 24