In this blog, we'll see how to use Angular's route guards to help with authentication.
Angular route guards are interfaces, which checks whether the router allows navigation for the user requested route.
There are different guard types we can use to protect our routes, each of then can be called on particular sequence:
Here we see an Example for canActivate guard type,
Eg: When a user is not authenticated and requested for the user dashboard route, we should not permit that route. the user can access that page only if a user is authenticated.
ng g generate components/UserDashboard
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserDashboardComponent } from './components/user-dashboard.component';
export const router: Routes = [
{path: 'user-dashboard' , component: UserDashboardComponent},
];
Here we haven't given any authguards for route, So everyone can access this page without any permission.
ng g service services/authguard
Now, this will add in your application app.module.ts in providers, So that we can use that service in your entire application.
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(public router: Router) {}
canActivate(): boolean {
const token = localStorage.getItem('token');
if (!token) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
Now, to provide permission for the specific route add this service for that route. At that time when a user hits the route first checks for the authguard based on the return response renders that page.
If it returns true, then page is visible for that user, otherwise user can't be visible that page
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserDashboardComponent } from './components/user-dashboard.component';
import { AuthGuard } from './services/authguard';
export const router: Routes = [
{path: 'user-dashboard' , component: UserDashboardComponent, canActivate: [AuthGuard]},
];