DEV Community

Cover image for Angular 8: Authentication using JSON Web Token (JWT) with HttpClient and HttpInterceptors.
Fabio Trotta
Fabio Trotta

Posted on

Angular 8: Authentication using JSON Web Token (JWT) with HttpClient and HttpInterceptors.

Preface

Using HttpInterceptors, the token (JWT) will be inserted in the 'Authorization' param of all REST calls headers subsequent to authentication made by our application.

 

Prerequisites

It is assumed that the saving in the LocalStorage of the JWT received from the backend at the time of authentication is already implemented.

Dependency Installation Required:

npm i -save angular2-jwt
Enter fullscreen mode Exit fullscreen mode
npm install @angular/http@latest
Enter fullscreen mode Exit fullscreen mode
npm install -save rxjs-compat
Enter fullscreen mode Exit fullscreen mode

 

Implementation

1) Create AuthService

ng g service auth
Enter fullscreen mode Exit fullscreen mode

2) Insert the following code in the AuthService class (auth.service.ts file created with the previous command) which will check the validity of the token:

import { Injectable } from @angular/core’;
import { tokenNotExpired } from angular2-jwt;
@Injectable()
export class AuthService {
    public getToken(): string {
        return localStorage.getItem(token);
}
public isAuthenticated(): boolean {
        const token = this.getToken();
        return tokenNotExpired(null, token);
    }
}
Enter fullscreen mode Exit fullscreen mode

3) Create the token.interceptor.ts file that will handle the application flow at each REST call. Here is the code of the TokenInterceptor class:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import { AuthService } from 'src/services/auth.service';
import { Observable } from 'rxjs';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(req)
     .pipe(
       tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
         // Successful authentication Secure API invoked successfully
        }
     }, (error) => {
     if (error instanceof HttpErrorResponse) {
      if (error.status === 401) {
       // Login error or invalid token.
      }
     }
    })
   );
  }
}
Enter fullscreen mode Exit fullscreen mode

In this class it will be possible to manage the behavior of the application in the event that the token is no longer valid (for example, redirecting the user to the login screen or refresher the token).

4) Add HttpInterceptors to providers in app.module.ts:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

 

Credits:
1) Angular Authentication: Using the Http Client and Http Interceptors
2) Angular Authentication with JWT (Image)

Top comments (1)

Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

Useful info. If someone is looking for basic info about JWT, check out devopedia.org/json-web-token