Authorization bearer token Angular 5
I suggest to use HttpInterceptor
for setting default HTTP headers on outgoing requests rather than adding an additional HTTP header to each call.
HTTP Client - Setting default headers @ angular.io
In your example you can do the following:
import { Http, Headers, Response } from '@angular/http';getLoggedInUser(auth_token): Observable<any> { const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${auth_token}` }) return this.http.get(apiUrl, { headers: headers })}
For get
requests, I used the following code and it works
import { HttpClient, HttpHeaders } from '@angular/common/http';getServerList(){ var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken')) }); return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, { headers: reqHeader });}
Two things:
headers.append(...)
does not mutate the headers object, so your authorization header is not being sent. You need to doheaders = headers.append(...)
Try
this.http.get<UserList[]>(this.mainUrl, { headers: headers });