Angular 6 - httpClient passing basic auth in httpOptions

user9855223 picture user9855223 · Jun 5, 2018 · Viewed 46.8k times · Source

I have a service in Angular 6 and I'm trying to change a record but it's saying I'm not authorized.

Right now I have this:

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

  update(id, title, content) {
    const updateData = { id: id, title: title, content: content };
      return this.http.put(`http://myurl/${id}`, updateData, httpOptions);
  }

My question is:

How to I add basic authorization to my httpOptions or do I add it direct to the update method?

Answer

Prachi picture Prachi · Jun 5, 2018

You can add basic authorization by appending it in headers, as below:

var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Basic " + btoa("username:password"));

const httpOptions = {
  headers: headers_object
};