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!

1

2 Answers 2

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:')
    })
};
Sign up to request clarification or add additional context in comments.

Comments

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 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.