Angular Routing Guards
Authguard interfaces of Angular help protect\safe guard important routes in your angular application based on authentication.
If you want to guard "product" route, it is simply a 4 step approach,
1) Firstly implement your JWT bearer token authentication code.Here is the injectable ApplicationAuthService which gets the auth token from browser's local storage.
- import { Injectable } from '@angular/core';
- @Injectable()
- export class ApplicationAuthService {
- constructor() {}
- private isTokenExpired(token: string) {
- const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
- return (Math.floor((new Date).getTime() / 1000)) >= expiry;
- }
- public isAuthenticated(): boolean {
- const token = localStorage.getItem('token');
- return this.tokenExpired(token)?false:true;
- }
- }
2) Implement CanActivate interface in your Guard service, AuthGuardService. Inject ApplicationAuthService into AuthGuardService.
- export class AuthGuardService implements CanActivate {}
3) Override canActivate() method, it returns true if the user is authenticated or navigates to Login URL
- import { Injectable } from '@angular/core';
- import { Router, CanActivate } from '@angular/router';
- import { AuthService } from './auth.service';
- @Injectable()
- export class AuthGuardService implements CanActivate {
- constructor(public authService: ApplicationAuthService , public router: Router) {}
- canActivate(): boolean {
- if (!this.authService.isAuthenticated()) {
- this.router.navigate(['signIn']);
- return false;
- }
- return true;
- }
- }
4) Add canActivate: [AuthGuard] to the desired routes(routes which needs to be protected)
- import { Routes, CanActivate } from '@angular/router';
- import { ProductComponent } from './product/product.component';
- import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';
- export const ROUTES: Routes = [
- { path: '', component: HomeComponent },
- {
- path: 'product',
- component: ProductComponent,
- canActivate: [AuthGuard]
- },
- { path: '**', redirectTo: '' }
- ];