Angular 8: Authentication using JSON Web Token (JWT) with HttpClient and HttpInterceptors.
Tags: angular, security, jwt, httpinterceptors
Published: 2021-03-31 21:43:39

# 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.

&nbsp;

# 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
```

```
npm install @angular/http@latest
```

```
npm install -save rxjs-compat
```

&nbsp;

# Implementation

**1)** Create `AuthService`

```
ng g service auth
```

**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:

```javascript
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);
    }
}
```

**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:

```javascript
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.
      }
     }
    })
   );
  }
}
```

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`:

```javascript
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 {}
```

&nbsp;

**Credits:**
**1)** [Angular Authentication: Using the Http Client and Http Interceptors](https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8)
**2)** [Angular Authentication with JWT (Image)](https://morioh.com/p/0f96284e0755)