In this tutorial, we are going to talk about implementing AuthGuard in an Angular application. AuthGuard is a route protection mechanism that allows or denies access to specific routes based on authentication or authorization conditions.
AuthGuard is essential for securing Angular applications, ensuring that users can only access authorized sections of the app. This is useful for applications with role-based access control, authentication flows, and restricted content.
Note:- AuthGuard works by intercepting navigation requests and determining if a user is allowed to proceed. If the user is not authenticated, they can be redirected to a login page or another appropriate route.
Let's start. Today, we will use Angular's built-in AuthGuard functionality to implement route protection. To create an AuthGuard, run the following command in your app terminal window:
ng generate guard auth
Once generated, update the auth.guard.ts
file to define the authentication logic:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Next, protect routes using AuthGuard in the app-routing.module.ts
file:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { DashboardComponent } from './dashboard/dashboard.component';
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '/login' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Congrats! You have successfully implemented route protection using AuthGuard in your Angular app. Now, let's explore handling unauthorized access.
Redirect users when they try to access restricted pages:
this.router.navigate(['/unauthorized']);
Handle user authentication status updates using an event listener:
this.authService.authStatusListener().subscribe(isAuthenticated => {
console.log("User authentication status changed:", isAuthenticated);
});
Note:- Ensure that the authentication service properly manages user login state and session persistence to maintain access control across page refreshes and app reloads.
I hope you enjoyed this tutorial. Keep learning!
Thanks!
0 Comments