I need to set some Authorization headers after the user has logged in, for every subsequent request.
To set headers for a particular request,
For Angular 5 and above, we can use HttpInterceptor for generalizing the request and response operations. This helps us avoid duplicating:
1) Common headers
2) Specifying response type
3) Querying request
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
requestCounter: number = 0;
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
responseType: 'json',
setHeaders: {
Authorization: `Bearer token_value`,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
// do stuff with response error if you want
}
});
}
}
We can use this AuthHttpInterceptor class as a provider for the HttpInterceptors:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthHttpInterceptor,
multi: true
}
],
exports: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
I like the idea to override default options, this seems like a good solution.
However, if you are up to extending the Http
class. Make sure to read this through!
Some answers here are actually showing incorrect overloading of request()
method, which could lead to a hard-to-catch errors and weird behavior. I've stumbled upon this myself.
This solution is based on request()
method implementation in Angular 4.2.x
, but should be future-compatible:
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {
ConnectionBackend, Headers,
Http as NgHttp,
Request,
RequestOptions,
RequestOptionsArgs,
Response,
XHRBackend
} from '@angular/http';
import {AuthenticationStateService} from '../authentication/authentication-state.service';
@Injectable()
export class Http extends NgHttp {
constructor (
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private authenticationStateService: AuthenticationStateService
) {
super(backend, defaultOptions);
}
request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if ('string' === typeof url) {
url = this.rewriteUrl(url);
options = (options || new RequestOptions());
options.headers = this.updateHeaders(options.headers);
return super.request(url, options);
} else if (url instanceof Request) {
const request = url;
request.url = this.rewriteUrl(request.url);
request.headers = this.updateHeaders(request.headers);
return super.request(request);
} else {
throw new Error('First argument must be a url string or Request instance');
}
}
private rewriteUrl (url: string) {
return environment.backendBaseUrl + url;
}
private updateHeaders (headers?: Headers) {
headers = headers || new Headers();
// Authenticating the request.
if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
}
return headers;
}
}
Notice that I'm importing original class this way import { Http as NgHttp } from '@angular/http';
in order to prevent name clashes.
The problem addressed here is that
request()
method has two different call signatures. WhenRequest
object is passed instead of the URLstring
, theoptions
argument is ignored by Angular. So both cases must be properly handled.
And here's the example of how to register this overridden class with DI container:
export const httpProvider = {
provide: NgHttp,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};
export function httpFactory (
xhrBackend: XHRBackend,
requestOptions: RequestOptions,
authenticationStateService: AuthenticationStateService
): Http {
return new Http(
xhrBackend,
requestOptions,
authenticationStateService
);
}
With such approach you can inject Http
class normally, but your overridden class will be magically injected instead. This allows you to integrate your solution easily without changing other parts of the application (polymorphism in action).
Just add httpProvider
to the providers
property of your module metadata.
The simplest of all
Create a config.ts
file
import { HttpHeaders } from '@angular/common/http';
export class Config {
url: string = 'http://localhost:3000';
httpOptions: any = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
})
}
}
Then on your service
, just import the config.ts
file
import { Config } from '../config';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class OrganizationService {
config = new Config;
constructor(
private http: HttpClient
) { }
addData(data): Observable<any> {
let sendAddLink = `${this.config.url}/api/addData`;
return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
tap(snap => {
return snap;
})
);
}
I think it was the simplest and the safest.
I has able to choose a simplier solution > Add a new Headers to the defaults options merge or load by your api get (or other) function.
get(endpoint: string, params?: any, options?: RequestOptions) {
if (!options) {
options = new RequestOptions();
options.headers = new Headers( { "Accept": "application/json" } ); <<<<
}
// [...]
}
Of course you can externalize this Headers in default options or whatever in your class. This is in the Ionic generated api.ts @Injectable() export class API {}
It is very quick and it work for me. I didn't want json/ld format.
Create a custom Http class by extending the Angular 2 Http
Provider and simply override the constructor
and request
method in you custom Http class. The example below adds Authorization
header in every http request.
import {Injectable} from '@angular/core';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpService extends Http {
constructor (backend: XHRBackend, options: RequestOptions) {
let token = localStorage.getItem('auth_token'); // your custom token getter function here
options.headers.set('Authorization', `Bearer ${token}`);
super(backend, options);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('auth_token');
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
if (!options) {
// let's make option object
options = {headers: new Headers()};
}
options.headers.set('Authorization', `Bearer ${token}`);
} else {
// we have to add the token to the url object
url.headers.set('Authorization', `Bearer ${token}`);
}
return super.request(url, options).catch(this.catchAuthError(this));
}
private catchAuthError (self: HttpService) {
// we have to pass HttpService's own instance here as `self`
return (res: Response) => {
console.log(res);
if (res.status === 401 || res.status === 403) {
// if not authenticated
console.log(res);
}
return Observable.throw(res);
};
}
}
Then configure your main app.module.ts
to provide the XHRBackend
as the ConnectionBackend
provider and the RequestOptions
to your custom Http class:
import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './services/http.service';
...
@NgModule({
imports: [..],
providers: [
{
provide: HttpService,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new HttpService(backend, options);
},
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [ AppComponent ]
})
After that, you can now use your custom http provider in your services. For example:
import { Injectable } from '@angular/core';
import {HttpService} from './http.service';
@Injectable()
class UserService {
constructor (private http: HttpService) {}
// token will added automatically to get request header
getUser (id: number) {
return this.http.get(`/users/${id}`).map((res) => {
return res.json();
} );
}
}
Here's a comprehensive guide - http://adonespitogo.com/articles/angular-2-extending-http-provider/
How about Keeping a Separate Service like follows
import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions} from '@angular/http';
@Injectable()
export class HttpClientService extends RequestOptions {
constructor(private requestOptionArgs:RequestOptions) {
super();
}
addHeader(headerName: string, headerValue: string ){
(this.requestOptionArgs.headers as Headers).set(headerName, headerValue);
}
}
and when you calling this from another place use this.httpClientService.addHeader("Authorization", "Bearer " + this.tok);
and you will see the added header eg:- Authorization as follows