In this article we are going to discuss about setting a common headers for all http calls using angular interceptor concept. If you are using angular version below 4.3 then check my previous post to achieve this. For improving security of the application we need to pass a token to all http request so that the same can be validated in the backend and decide user session is valid or not. We can pass token to individual http request and also do the same using interceptor as well. Using interceptor we can pass token to all http request.
1. Set headers for single http request
2. Set headers for all http request using interceptor
1. Set headers for single http request
Let us check one use case where we need to pass headers for only some of the http request.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CommonService {
_url: string;
constructor(private http: HttpClient) { }
sendData(item) {
this._url = '/api/add/data';
return this.http.post(this._url, item, {
headers: { 'authTicket': '000001' }
})
.map((response: Response) => {
return response;
});
}
}
Here we are passing headers to a particular http request. We can pass multiple headers as well. Check below code for that.
return this.http.post(this._url, item, {
headers: { 'authTicket': '000001', 'otherToken': '90909' }
})
If you want to know more about API calls check this link.
2. Set headers for all http request using interceptor
In the above example we have explained about passing header to single http calls. But in real time scenario we need to pass a token to all http request. Most of the applications follow the same as it is very important for application security. We cannot follow above approach for this, as our application may contains 100+ https request. We can use an interceptor for passing token to all http request. Check below interceptor code.
Interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class SecurityTokenInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
AuthTicket: 'token_001'
}
})
return next.handle(request);
}
}
We are done with our interceptor, in the above example we have hardcoded the token as token_001. Before testing the result modify your module file like below. Don't forget to import HTTP_INTERCEPTORS.
Module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// Components
import { AppComponent } from './app.component';
import { GeneralComponent } from './dashboard/general/general.component';
// Services
import { CommonService } from './services/common.service';
//interceptor
import { SecurityTokenInterceptor } from './interceptor';
@NgModule({
declarations: [
AppComponent,
GeneralComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: SecurityTokenInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
We are done. Now create some http request calls and test it. You can open the network tab and check headers are correctly passed or not.
In the above example we have hardcoded the token. But in real time you need to get it from a login API or some other apis depending on your project use case. Check below example to get a token from a service file.
Service file
import { Injectable } from '@angular/core';
@Injectable()
export class CommonService {
token: string;
getToken() {
return this.token;
}
setToken(token) {
this.token = token
}
}
Here we are setting the token as soon we get from backend and you can get the sane anywhere by calling getToken method. Read more about setting and getting data from service here. Check updated interceptor code below.
Updated interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { CommonService } from './services/common.service';
@Injectable()
export class SecurityTokenInterceptor implements HttpInterceptor {
constructor(public auth: CommonService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
AuthTicket: this.auth.getToken()
}
})
return next.handle(request);
}
}
We have updated our interceptor to read data from a service file. Now create some http calls and test the result. I have written about authentication flow using auth guard.
Read more about here: - Login authentication flow using angular auth guard.
You can combine both article logic to implement a perfect login flow.
In this article we have discussed about creating an interceptor for passing a common header to all http calls.
Related Info
1. Share data between Angular components - 7 methods.
2. Rating star component using Angular.
It works like a charm, thanks for the simple explanation.
ReplyDeleteI have implemented this but my headers are added in access-control-request-headers label which is unable to retrieve in java side.
ReplyDeleteCheck whether your backend server is accepting those header names.
Delete