How to use AuthGuard For Angular 17 routes?
Last Updated :
01 May, 2024
In Angular applications, it is often necessary to protect certain routes to prevent unauthorized access. The Angular Router provides a feature called Route Guards, which allows you to control access to routes based on specific conditions. One of the commonly used Route Guards is AuthGuard, which checks if the user is authenticated before allowing access to a particular route. In this article, we will explore how to set up and use the AuthGuard in an Angular 17 application.
Prerequisites:
Approach
- Create AuthGuard Service: Start by creating an AuthGuard service in your Angular app. Implement the
CanActivate
interface to control access to routes based on user authentication. - Authenticate Users: Implement authentication logic within the AuthGuard service to determine if a user is authenticated and allowed to access a route.
- Provide the AuthGuard: Ensure the AuthGuard service is provided either at the root level or within a specific module to make it available throughout the app.
- Apply AuthGuard to Routes: Add the AuthGuard to the routes that require protection by specifying it in the
canActivate
property of the route definition. - Handle Redirects: Handle redirection for unauthorized users within the AuthGuard service to ensure a smooth user experience and prevent unauthorized access to protected routes.
Steps to use AuthGuard
Step 1: Create an angular application
Once you have the prerequisites, you can use the below commands to create an angular application.
ng new auth-gaurds
cd auth-gaurds
Step 2: Create routes to protect
Before we create and implement the auth guard, first we need to make some components we need to protect. We will create two components auth and dashboard,
ng g c auth
ng g c dashboard
We will create a simple auth service file so it will be easy to manage auth state in our application. Also we will update our app.router.ts and app, auth and dashboard components to have a basic skeleton of a real world application.
Step 3: Create Auth Service:
We can use the below command to create the service file using angular cli.
ng g s auth
Folder Structure:

Dependencies:
"dependencies": {
"@angular/animations": "^17.2.0",
"@angular/common": "^17.2.0",
"@angular/compiler": "^17.2.0",
"@angular/core": "^17.2.0",
"@angular/forms": "^17.2.0",
"@angular/platform-browser": "^17.2.0",
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/router": "^17.2.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example: This example demonsrates Angular routes.
HTML
<!-- auth.component.html -->
<div>
<p class="title">Sign In</p>
<form [formGroup]="signInForm" (ngSubmit)="signIn()">
<input type="email" name="email" formControlName="email">
<br>
<button type="submit">Sign In</button>
</form>
</div>
HTML
<!-- dashboard.component.html -->
<div>
<p class="title">Dashboard</p>
<p>Welcome, {{ email }}</p>
<button (click)="signOut()">Sign Out</button>
</div>
HTML
<!-- app.component.html -->
<nav>
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
<a routerLink="/auth" routerLinkActive="active">Sign In</a>
</nav>
<router-outlet></router-outlet>
CSS
/* auth.component.scss */
div {
width: 600px;
border: 1px solid #ccc;
padding: 16px;
margin: 16px auto;
p {
font-size: 28px;
}
input {
width: 100%;
margin-bottom: 8px;
}
button,
input {
height: 40px;
font-size: large;
}
}
CSS
/* dashboard.component.scss */
div {
width: 600px;
border: 1px solid #ccc;
padding: 16px;
margin: 16px auto;
p {
font-size: 28px;
}
button {
height: 40px;
font-size: large;
}
}
CSS
/* app.component.scss */
nav {
width: 600px;
margin: 0 auto;
padding: 16px;
display: flex;
justify-content: space-between;
font-size: 20px;
a {
color: black;
}
a:hover {
cursor: pointer;
text-decoration: underline;
}
.active {
color: blue;
}
}
JavaScript
// auth.component.ts
import { Component } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-auth',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './auth.component.html',
styleUrl: './auth.component.scss',
})
export class AuthComponent {
signInForm = new FormGroup({
email: new FormControl<string>('', [Validators.required]),
});
constructor(private authService: AuthService) { }
signIn() {
if (this.signInForm.valid) {
this.authService.signIn(this.signInForm.value.email as string);
}
}
}
JavaScript
//auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AuthService {
public isAuth = new BehaviorSubject<boolean>(false);
constructor(private router: Router) {
this.autoSignIn();
}
autoSignIn() {
if (localStorage.getItem('email')) {
this.isAuth.next(true);
this.router.navigate(['/dashboard']);
}
}
signIn(email: string) {
localStorage.setItem('email', email);
this.isAuth.next(true);
this.router.navigate(['/dashboard']);
}
signOut() {
localStorage.removeItem('email');
this.isAuth.next(false);
this.router.navigate(['/auth']);
}
}
JavaScript
// dashboard.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [],
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
})
export class DashboardComponent {
email = localStorage.getItem('email');
constructor(private authService: AuthService) { }
signOut() {
this.authService.signOut();
}
}
JavaScript
// app.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink, RouterLinkActive],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {
title = 'auth-gaurds';
constructor(public authService: AuthService) { }
}
Once you have made this changes, you should have a simple working application as shown below.
No auth guardStep 4: Protecting dashboard route
Notice that when we are not signed in and we try to click the dashboard nav anchor, we can still see the dashboard component. Well, we will need to create an auth guard in order to protect it.
Before we create the file let us see types of auth guard available in angular.
- CanActivate: Guards the entry to a route, deciding if the user can access it or not (e.g., authentication check).
- CanActivateChild: Guards the entry to child routes within a parent route, allowing or denying access to specific child routes.
- CanDeactivate: Guards the exit from a route or component, prompting the user before navigating away (e.g., unsaved changes check).
- CanMatch: Guards whether a specific route should be considered during navigation or not, dynamically enabling or disabling routes based on conditions.
We will of course create a CanActivate guard in order to protect the dashboard route.
ng g g auth
You will be prompted to select type for the guard, you can select CanActivate here.
Types of guardsStep 5: Implementing the auth gaurd
Now we need to use the guard we created, for this we can update our app.router.ts as below
JavaScript
// app.router.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
export const routes: Routes = [
{
path: 'auth',
loadComponent: () =>
import('./auth/auth.component').then((m) => m.AuthComponent),
},
{
path: 'dashboard',
loadComponent: () =>
import('./dashboard/dashboard.component').then(
(m) => m.DashboardComponent
),
canActivate: [authGuard],
},
];
JavaScript
// auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuth.value == false) {
router.navigate(['/auth']);
return false;
}
return authService.isAuth.value;
};
Once we have added authGuard to canActivate property, we can see that we can no longer visit the dashboard route when we aren't signed in.
With auth guard
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read