20

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?

7 Answers7

37

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
};
Prachi
  • 3,022
  • 11
  • 31
  • This is what i was after but how do I add that to this: const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; –  Jun 05 '18 at 08:02
  • Getting an error: Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; –  Jun 05 '18 at 08:15
  • You have to assign header variable in header parameter. H must be in lowercase. I have updated the solution to avoid the confusion. – Prachi Jun 05 '18 at 08:54
  • 3
    `new Headers();` should be `new HttpHeaders()` – Pardeep Jain Jun 05 '18 at 09:13
  • @PardeepJain It worked in Angular 4. I have updated the answer for Angular 5/6. Thanks. – Prachi Jun 05 '18 at 09:15
  • Yes, because OP is using v-5/6 as per question details – Pardeep Jain Jun 05 '18 at 09:18
  • Yes, I didn't note that. – Prachi Jun 05 '18 at 09:19
7

Just add your token/authorization in the headers like this -

let httpHeaders = new HttpHeaders()
              .set('authorization', this.authorizationHeaderValue)
              .set('Content-Type', application/json); 

Both have methods such as set and append. set constructs a new body with a new value and append constructs a new body with an appended value

PS: Here I am assuming the variable (this.authorizationHeaderValue) value is included value like Bearer or Basic or whatever needed, Change it accordingly.

For more read here

Pardeep Jain
  • 71,130
  • 29
  • 141
  • 199
  • it's probably the comma on line 2 – Joakim Jun 05 '18 at 17:49
  • 1
    Ohh , that was just a typo mistake. Didn't deserve downvote for this anyways thanks for pointing out :) – Pardeep Jain Jun 06 '18 at 04:43
  • Your Authroization header is wrong. "Authorization" and the value usually has the word "Basic " or "Digest " or "Bearer " in front of the actual token (not the blank space). If this is an OAuth token, then you'd use "Bearer " in front of the authtoken – Kevin M May 10 '19 at 17:22
  • @KevinM you are right but I am assuming (As best practice) to be a string inlcuding `Bearer or Basic etc` in the variable named here `this.authToken`. Seems it's self understood – Pardeep Jain May 13 '19 at 04:58
  • 1
    I wondered if that's what you were implying. But with a variable name of just "authToken" I assumed it was JUST the token itself, not the Authorization header string (I probably would name the variable "authorizationHeaderValue" or something to that effect. – Kevin M May 14 '19 at 13:35
  • 1
    You are right, Variable name could be better instead of simply `authToken`, Will update the variable name as you suggested. thanks @KevinM – Pardeep Jain May 15 '19 at 12:30
  • @KevinM This is improtant anyways, I loved it! – Pardeep Jain May 17 '19 at 05:09
7

Looking at the angular.io documentation, it's pretty straightforward.

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

And you can use the httpOptions constant as you did.

For more information: https://angular.io/guide/http#adding-headers

Mehdi Benmoha
  • 2,992
  • 3
  • 18
  • 37
  • Hi friend, I have 2 services for example, authservice to login and userService to get data, after to login i set localstorage and create token and in userService I've trying to get token but without success const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('token') }) }; its don't get token, any idea ? – Rafael Moura May 06 '19 at 19:37
2

httpClient passing basic auth in httpOptions is different in Angular 6

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

const httpOptions = {
  headers: httpHeaders
};

update(id, title, content) {
    const updateData = { id: id, title: title, content: content };
      return this.http.put(`http://myurl/${id}`, updateData, httpOptions);
  }
Rohit.007
  • 3,040
  • 2
  • 17
  • 28
1
const httpOptions = {
  headers: new HttpHeaders(
    {
      'Content-Type': 'application/json',
      'Authorization': `Basic ` + btoa('user:password'),
    }
  )
};


return this.http.post<any>(
      `apilink`,{},
      httpOptions
    ).pipe(map(res => {
      return res;
}));
0
import { HttpClient, HttpHeaders } from '@angular/common/http';

var headers = new HttpHeaders();

var token = localStorage.getItem('token');

headers.append('Content-Type', 'application/json');

headers.append("Authorization", "Basic " + token));

const httpOptions = {
  headers: headers
};
Community
  • 1
  • 1
0

Many servers require extra headers for save operations. For example, a server might require an authorization token, or "Content-Type" header to explicitly declare the MIME type of the request body. In your case, you can do basic authorization by following code.

import { HttpHeaders } from '@angular/common/http'; 
const httpOptions = {headers: new HttpHeaders({
'Content-Type':  'application/json',
Authorization: 'my-auth-token' })};

you can update the authorization header before making the next request

httpOptions.headers =  httpOptions.headers.set('Authorization', 'my-new-auth-token');