Navigation

Tuesday 24 September 2019

Angular 6: Add a Http Authentication Bearer token by implementing HttpInterceptor.

 Step 1:       
Create a folder with name '_helper' and in that service file 'Token.interceptor.ts'. Copy and paste the code shown below.

 _helpers => token.interceptor.ts


import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { LocalStorageServiceService } from '../Service/local-storage-service.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(private _LocalStorage: LocalStorageServiceService) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available     
        let Token = this._LocalStorage.getValueOnLocalStorage('Token');
        if (Token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${Token}`
                }
            });
        }
        return next.handle(request);
    }
}


 Step 2:
In 'app.module.ts' configure the dependency injector 'HTTP_INTERCEPTORS' and set the dependency injector in 'provider'. The multi-provider token which represents the array of 'HttpInterceptor' that are registered.



import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './_helpers/token.interceptor';

providers: [  
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
],



Step 3:
Create service 'local-storage.service.ts' for the session storage.



import { Injectable, Inject } from '@angular/core';
import { SESSION_STORAGE, StorageService } from 'angular-webstorage-service';


@Injectable({
    providedIn: 'root'
})
export class LocalStorageService {

    constructor(@Inject(SESSION_STORAGE) private storage: StorageService) { }

    public storeOnLocalStorage(_key: string, _value: string): void {
        // insert updated array to local storage
        this.storage.set(_key, _value);      
    }

    public getValueOnLocalStorage(_key: string): string {
        return this.storage.get(_key);
    }
    public removeStoreOnLocalStorage(_key: string): void {
        this.storage.remove(_key);
    }
    public removeAllAdminStoreOnLocalStorage(): void {     
        this.storage.remove("LoggedInUserId");      
        this.storage.remove("Token");
    }   
}


Step 4 :
'login.component.ts' the component that has the login() to validate the user and store the token that has generated by service.



Login() { 
    let ApplicantObj = {
        EmailID: this.Username,
        Password: this.Password,
        UserType: 2
    }
    //AdminService use to call api
    this._adminService.ValidateUser(ApplicantObj)
        .subscribe(vApplicant => {           
            this.Applicants = vApplicant;
            if (this.Applicants.length > 0) {              
                //_LocalStorage is a service that can store value locally. 
                //You can create service just like the local-storage.service.ts file.'
                this._LocalStorage.storeOnLocalStorage("LoggedInUserId", this.Applicants[0].userId.toString());             
                this._LocalStorage.storeOnLocalStorage("Token", this.Applicants[0].token);              
                this.router.navigate(['/home']);
            }
            else {              
                this._ToastrService.error("Invalid username and password");
            }
        })
}

No comments:

Post a Comment