Quick Summary: Explore the implementation of Auth Guard in Angular to enhance security in your applications. Learn how to use Angular Route Guards for authentication, ensuring that only authorized users can access specific routes and components within your Angular applications.
In modern web applications, ensuring that users have appropriate access to different parts of your app is crucial. Angular provides a robust mechanism for handling authentication and authorization through Route Guards, specifically the Auth Guard.
Auth Guard allows developers to protect routes by checking whether a user is authenticated before granting access. This not only secures sensitive data but also improves user experience by redirecting unauthorized users to appropriate pages. In this guide, we'll dive deep into how to set up and implement Auth Guard in Angular, making your applications more secure and efficient.
Let’s start!
Key Takeaways
- Route guards are an important feature in Angular for securing routes and preventing unauthorized access to protected content.
- Angular provides several types of route guards, including CanActivate, CanActivateChild, CanDeactivate, and CanLoad.
- It is essential to store and retrieve user authentication status using local storage to maintain the user's authentication status across the application's components and routes.
- Using route guards for authentication enhances the security of Angular applications and provides a better user experience by preventing unauthorized access to protected content.
What are Route Guards in Angular?
An angular route guard called Auth Guard is used to shield routes from unauthorised or unauthenticated users. The canActivate interface, which implements a canActivate function that determines whether the current user has authorization to activate the given route, is used to implement it.
Angular’s Route Guards are interfaces that allow angular developers to grant or remove access from specific parts of the navigation. The decision is made based on the ‘true’ or ‘false’ return value from a class that implements the given guard interface. There are different types of Route Guards in angular, and each one is known as ‘particular sequence.’
5 Different types of Route Guards are as follows:
- CanActivate - Controls if a route can be activated
- CanActivateChild - Controls if children of the route can be activated
- CanDeactivate - Controls if the user can leave the route
- CanLoad - Controls if the route be loaded
- Resolve - Controls data resolution before the route is activated
Steps to Create Auth Guard in Angular
Creating a route guard is pretty simple, and all it takes is three steps to make it happen. Here’s how you can create it.
Step 1 - Create an Authentication Service
We will be using one of the most popular authentication methods here: JSON Web Tokens (JWT), to authenticate users. So the first step is to create the auth.service.ts, which will be responsible for handling the authentication.
ng g service auth
This will help you create the authentication service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
isLoggedIn() {
const token = localStorage.getItem('token'); // get token from local storage
const payload = atob(token.split('.')[1]); // decode payload of token
const parsedPayload = JSON.parse(payload); // convert payload into an Object
return parsedPayload.exp > Date.now() / 1000; // check if token is expired
}
}
isLoggedIn() function will attain the token from local storage. Then, the validity of the token’s payload will be checked concerning its expiration time.
Read our other blog to know the features of AngularJS in detail.
Step 2 - Create an Authentication Service
Now you can use the command given below to generate the guard.
ng g guard auth
Once that’s done, you will see auth.guard.ts that will implement the CanActivate interface.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']); // go to login if not authenticated
return false;
}
return true;
}
}
Using canActivate() method, an instance of Authentication service and return will be used to check whether the user is logged in or not. Thus, the user will easily be redirected to /login route if they are not logged in.
Step 3 - Use the Guard Inside Routes
A property kn