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
npm install @angular/http@latest
npm install -save rxjs-compat
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:
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:
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
:
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 {}
Credits:
1) Angular Authentication: Using the Http Client and Http Interceptors
2) Angular Authentication with JWT (Image)
Top comments (1)
Useful info. If someone is looking for basic info about JWT, check out devopedia.org/json-web-token