Securing Angular Applications with AuthGuard

Securing Angular Applications with AuthGuard

Securing Angular Applications with AuthGuard

Security is a crucial aspect of any web application. In Angular, one of the primary tools for securing routes is the AuthGuard. This blog will guide you through the process of setting up an AuthGuard to protect routes and ensure only authenticated users can access certain parts of your application.


What is an AuthGuard?


An AuthGuard is a service that implements the CanActivate interface. It determines whether a route can be activated or not based on certain conditions, typically related to user authentication and authorization.


Setting Up AuthGuard


Let's walk through a step-by-step process to set up an AuthGuard in an Angular application.


Step 1: Creating a New Angular Project


First, create a new Angular project if you don't have one already:


ng new auth-guard-demo
cd auth-guard-demo


Step 2: Generating the AuthGuard


Generate a new AuthGuard using the Angular CLI:


ng generate guard auth


This command will create a new guard file auth.guard.ts with a basic structure.


Step 3: Implementing the AuthGuard Logic


Open auth.guard.ts and implement the CanActivate interface. Here, we'll add some basic logic to check if the user is authenticated.


auth.guard.ts


import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service'; // Assume we have an AuthService

@Injectable({
 providedIn: 'root'
})
export class AuthGuard implements CanActivate {

 constructor(private authService: AuthService, private router: Router) {}

 canActivate(): boolean {
  if (this.authService.isLoggedIn()) {
   return true;
  } else {
   this.router.navigate(['/login']);
   return false;
  }
 }
}


In this example, the AuthGuard uses an AuthService to check if the user is logged in. If the user is not logged in, they are redirected to the login page.


Step 4: Creating the AuthService


Let's create a simple AuthService to handle authentication logic.


auth.service.ts


import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root'
})
export class AuthService {
 private loggedIn = false;

 login() {
  this.loggedIn = true;
 }

 logout() {
  this.loggedIn = false;
 }

 isLoggedIn() {
  return this.loggedIn;
 }
}


Step 5: Protecting Routes with AuthGuard


Now, let's protect certain routes using the AuthGuard. Open your app-routing.module.ts file and modify the routes to use the guard.


app-routing.module.ts


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
 { path: '', component: HomeComponent },
 { path: 'login', component: LoginComponent },
 { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }


In this example, the DashboardComponent is protected by the AuthGuard. Only authenticated users can access this route.


Step 6: Creating the Components


For this example, let's create a LoginComponent and a DashboardComponent.


Generating Components


ng generate component home
ng generate component login
ng generate component dashboard


login.component.ts


import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})
export class LoginComponent {

 constructor(private authService: AuthService, private router: Router) {}

 login() {
  this.authService.login();
  this.router.navigate(['/dashboard']);
 }
}


login.component.html


<h2>Login</h2>
<button (click)="login()">Login</button>


dashboard.component.ts


import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';

@Component({
 selector: 'app-dashboard',
 templateUrl: './dashboard.component.html',
 styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent {

 constructor(private authService: AuthService, private router: Router) {}

 logout() {
  this.authService.logout();
  this.router.navigate(['/']);
 }
}


dashboard.component.html


<h2>Dashboard</h2>
<button (click)="logout()">Logout</button>


Conclusion


In this blog, we have explored how to set up an AuthGuard in Angular to protect routes and ensure only authenticated users can access certain parts of your application. By implementing an AuthGuard, you can enhance the security of your Angular application and provide a better user experience.


Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts