How to Implement Authentication Guards in Angular SPAs

How to Implement Authentication Guards in Angular SPAs

When developing Single Page Applications (SPAs) with Angular, implementing authentication guards is essential for securing routes and ensuring only authorized users can access certain parts of your application. This article will guide you through the process of implementing authentication guards in Angular.

What are Authentication Guards?

Authentication guards are services that control access to certain routes in your Angular application based on user authentication status. They help protect your application from unauthorized access by redirecting users who are not authenticated.

Types of Guards in Angular

Angular provides several types of guards, but for authentication purposes, we primarily use:

  • CanActivate: This guard checks if a route can be activated based on certain conditions.
  • CanActivateChild: This guard secures child routes based on parent route conditions.

Creating an Authentication Service

Before implementing guards, you need an authentication service to manage user login states. Here’s a simple example of an authentication service:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private loggedIn = new BehaviorSubject(false);
login() {
    this.loggedIn.next(true);
  }
logout() {
    this.loggedIn.next(false);
  }
isLoggedIn() {
    return this.loggedIn.asObservable();
  }
}

Implementing CanActivate Guard

Now, let's create a CanActivate guard that restricts access to certain routes based on the user's authentication status:

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 {
    
    let isLoggedIn: boolean;
    this.authService.isLoggedIn().subscribe(loggedIn => {
      isLoggedIn = loggedIn;
    });
if (!isLoggedIn) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

Registering the Guard

To use the AuthGuard, register it in your routing module:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Conclusion

Implementing authentication guards in your Angular SPAs is a crucial step in safeguarding your application. By utilizing the CanActivate guard, you can easily manage user access and enhance the overall security of your application. Don’t forget to manage user authentication states effectively in your services to ensure a seamless user experience.

Adopting these practices will not only secure your application but will also improve the user experience by directing users appropriately based on their authentication status.