Ng5- HttpInterceptors - authroization token in API
------------------------------------------------------------
Method: 1
=========
Angular Interceptors:-
Interceptors are the mechanism where we can operate on the outgoing request and the incoming response.
Setting up Interceptors:-
To set up interceptor, we need a class which will be injectable class and implementing the HttpInterceptor. When we implement this Interface, then we have a method called intercept which has the body like below.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {}
It has two parameters "req" and "next" which are HttpRequest and HttpHandler respectively.
src/app/auth/HeaderInterceptor.ts
----------------------------------
import { Injectable } from '@angular/core'
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const dummyrequest = req.clone({
setHeaders: {
'AuthKey': '12345', 'DeviceID': '85645',
'content-type': 'application/json',
'Authorization': 'Bearer My-token'
}
})
console.log("Cloned Request");
console.log(dummyrequest);
return next.handle(dummyrequest);
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import {FormsModule} from '@angular/forms'
import { AppComponent } from './app.component';
import {HeaderInterceptor} from './Interceptors/HeaderInterceptor'
@NgModule({
declarations: [
AppComponent,
EmpoyeeHomeComponent
],
imports: [
BrowserModule,HttpClientModule,FormsModule
],
providers: [EmployeeDataService,
{ provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Ref: https://www.c-sharpcorner.com/article/angular-5-http-client-interceptors/
Method:2
=========
ANGULAR 5 HTTPINTERCEPTOR – ADD BEARER TOKEN TO HTTPCLIENT REQUESTS
--------------------------------------------------------------------
In this article I will describe how to add a Http Authentication Bearer token to each request done from Angular via HttpClient by implementing a Angular 5 HttpInterceptor. This way the bearer token has not be added to each request separately while doing Ajax request e.g. to a REST api. This is for example useful, if you have some api that is protected by OAuth and you have to sent a JWT token in order to get access.
app.module.ts
---------------
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
...
providers: [
...
{ provide: HTTP_INTERCEPTORS,
useClass: CustomHttpInterceptor,
multi: true
},
...
})
CustomHttpInterceptor.ts:
---------------------------
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { MsalService } from '../services/msal.service';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/fromPromise';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private msalService: MsalService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return Observable.fromPromise(this.handleAccess(request, next));
}
private async handleAccess(request: HttpRequest<any>, next: HttpHandler):
Promise<HttpEvent<any>> {
const token = await this.msalService.getAccessToken();
let changedRequest = request;
// HttpHeader object immutable - copy values
const headerSettings: {[name: string]: string | string[]; } = {};
for (const key of request.headers.keys()) {
headerSettings[key] = request.headers.getAll(key);
}
if (token) {
headerSettings['Authorization'] = 'Bearer ' + token;
}
headerSettings['Content-Type'] = 'application/json';
const newHeader = new HttpHeaders(headerSettings);
changedRequest = request.clone({
headers: newHeader});
return next.handle(changedRequest).toPromise();
}
}
option:3
==========
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class BearerTokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentToken = localStorage.getItem('AccessToken'); // get toeken from API i.e APP_INITIALIZER
console.log(currentToken,'<---jwt token Http Interceptors');
if (currentToken && currentToken != null) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentToken}`
}
});
}
return next.handle(request);
}
}
A couple of things to notice here. Since I’m working with async / await and I use Promises in my code and the intercept method returns an Observable, I have to convert my Promise to an Observable using the Observable.fromPromise method.
In the handleAccess method I get my access token from my msalService. This is a service for handling login / access etc. using Microsoft Authentication Library for JavaScript (In my case Azure AD B2C).
The next step is to actually add the token to the HttpClient request.
Immutable Request / RequestHeader
One very important point is, that you cannot simply set or add new headers to the request object.
The request and header objects are immutable. Even if you change something by adding a new header or trying to set some header, this will not work. This took me a while to figure out, because the api of these objects allows you to do so. But the changes you make are then not reflected in the requests you make later on
REf: https://www.illucit.com/en/angular/angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/
------------------------------------------------------------
Method: 1
=========
Angular Interceptors:-
Interceptors are the mechanism where we can operate on the outgoing request and the incoming response.
Setting up Interceptors:-
To set up interceptor, we need a class which will be injectable class and implementing the HttpInterceptor. When we implement this Interface, then we have a method called intercept which has the body like below.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {}
It has two parameters "req" and "next" which are HttpRequest and HttpHandler respectively.
src/app/auth/HeaderInterceptor.ts
----------------------------------
import { Injectable } from '@angular/core'
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const dummyrequest = req.clone({
setHeaders: {
'AuthKey': '12345', 'DeviceID': '85645',
'content-type': 'application/json',
'Authorization': 'Bearer My-token'
}
})
console.log("Cloned Request");
console.log(dummyrequest);
return next.handle(dummyrequest);
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import {FormsModule} from '@angular/forms'
import { AppComponent } from './app.component';
import {HeaderInterceptor} from './Interceptors/HeaderInterceptor'
@NgModule({
declarations: [
AppComponent,
EmpoyeeHomeComponent
],
imports: [
BrowserModule,HttpClientModule,FormsModule
],
providers: [EmployeeDataService,
{ provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Ref: https://www.c-sharpcorner.com/article/angular-5-http-client-interceptors/
Method:2
=========
ANGULAR 5 HTTPINTERCEPTOR – ADD BEARER TOKEN TO HTTPCLIENT REQUESTS
--------------------------------------------------------------------
In this article I will describe how to add a Http Authentication Bearer token to each request done from Angular via HttpClient by implementing a Angular 5 HttpInterceptor. This way the bearer token has not be added to each request separately while doing Ajax request e.g. to a REST api. This is for example useful, if you have some api that is protected by OAuth and you have to sent a JWT token in order to get access.
app.module.ts
---------------
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
...
providers: [
...
{ provide: HTTP_INTERCEPTORS,
useClass: CustomHttpInterceptor,
multi: true
},
...
})
CustomHttpInterceptor.ts:
---------------------------
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { MsalService } from '../services/msal.service';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/fromPromise';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private msalService: MsalService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return Observable.fromPromise(this.handleAccess(request, next));
}
private async handleAccess(request: HttpRequest<any>, next: HttpHandler):
Promise<HttpEvent<any>> {
const token = await this.msalService.getAccessToken();
let changedRequest = request;
// HttpHeader object immutable - copy values
const headerSettings: {[name: string]: string | string[]; } = {};
for (const key of request.headers.keys()) {
headerSettings[key] = request.headers.getAll(key);
}
if (token) {
headerSettings['Authorization'] = 'Bearer ' + token;
}
headerSettings['Content-Type'] = 'application/json';
const newHeader = new HttpHeaders(headerSettings);
changedRequest = request.clone({
headers: newHeader});
return next.handle(changedRequest).toPromise();
}
}
option:3
==========
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class BearerTokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentToken = localStorage.getItem('AccessToken'); // get toeken from API i.e APP_INITIALIZER
console.log(currentToken,'<---jwt token Http Interceptors');
if (currentToken && currentToken != null) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentToken}`
}
});
}
return next.handle(request);
}
}
A couple of things to notice here. Since I’m working with async / await and I use Promises in my code and the intercept method returns an Observable, I have to convert my Promise to an Observable using the Observable.fromPromise method.
In the handleAccess method I get my access token from my msalService. This is a service for handling login / access etc. using Microsoft Authentication Library for JavaScript (In my case Azure AD B2C).
The next step is to actually add the token to the HttpClient request.
Immutable Request / RequestHeader
One very important point is, that you cannot simply set or add new headers to the request object.
The request and header objects are immutable. Even if you change something by adding a new header or trying to set some header, this will not work. This took me a while to figure out, because the api of these objects allows you to do so. But the changes you make are then not reflected in the requests you make later on
REf: https://www.illucit.com/en/angular/angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/