Protecting Routes With Auth Guard In Angular 7

Introduction

 
Here, today, we will learn about protecting our routes with Auth Guard in Angular 7. As we all know that our system should be secure, i.e., without proper authentication, no one should access the protected information of our web application.
 
So, the question is how can we avoid this scenario; i.e., no one can access sensitive information without proper authentication. This can be achieved by the use of Auth guard in Angular 7.
 
Auth-guard makes use of CanActivate interface and it checks for if the user is logged in or not. If it returns true, then the execution for the requested route will continue, and if it returns false, that the requested route will be kicked off and the default route will be shown.
 
Prerequisites
  • Basic knowledge of Angular 7
  • Visual Studio Code
  • Angular CLI must be installed
  • NodeJS must be installed
Let’s get started.
  
Create a new application in Angular 7 by using your favorite code editor.
  1. ng new auth-guard-demo --routing 
After creating, open the newly created project and from the terminal, create two files for Auth and Authentication by typing the following command. 
  1. ng g service ./_service/auth-guard  
  2. ng g service ./_service/authentication 
Create two components by typing the following commands. 
  1. ng g c home  
  2. ng g c login 
Open the auth-guard.service.ts file and add the code in it.
  1. import { Injectable } from '@angular/core';  
  2. import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  
  3. @Injectable({ providedIn: 'root' })  
  4. export class AuthGuard implements CanActivate {  
  5.     constructor(private _router: Router) { }  
  6.     canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {  
  7.         if (localStorage.getItem('currentUser')) {  
  8.             return true;  
  9.         }  
  10.         this._router.navigate(['']);  
  11.         return false;  
  12.     }  

Code for authentication.service.ts file. 
  1. import { Injectable } from '@angular/core';  
  2. @Injectable({  
  3.   providedIn: 'root'  
  4. })  
  5. export class AuthenticationService {  
  6.   login(username: string, password: string) {  
  7.     if (username == "admin" && password == "admin") {  
  8.       localStorage.setItem('currentUser'"loggedin");  
  9.       return true;  
  10.     }  
  11.   }  
  12.   logout() {  
  13.     localStorage.removeItem('currentUser');  
  14.   }  
  15.   public get loggedIn(): boolean {  
  16.     return (localStorage.getItem('currentUser') !== null);  
  17.   }  

Open the home.component.ts file and add the code in it. 
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Router } from '@angular/router';  
  3. import { AuthenticationService } from '../_service/authentication.service';  
  4. @Component({  
  5.   selector: 'app-home',  
  6.   templateUrl: './home.component.html',  
  7.   styleUrls: ['./home.component.css']  
  8. })  
  9. export class HomeComponent implements OnInit {  
  10.   constructor(private router: Router, private authenticationService: AuthenticationService) { }  
  11.   ngOnInit() {  
  12.   }  
  13.     
  14.   logout() {  
  15.     this.authenticationService.logout();  
  16.     this.router.navigate(['']);  
  17.   }  

Code for home.component.html file.
  1. <div class="container">    
  2.   <h1>You are successfully logged in</h1>    
  3.   <button (click)="logout()" class="btn btn-danger">Logout</button>    
  4. </div>   
Open the login.component.ts file and add the code in it.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { AuthenticationService } from '../_service/authentication.service';  
  3. import { Router } from '@angular/router';  
  4. @Component({  
  5.   selector: 'app-login',  
  6.   templateUrl: './login.component.html',  
  7.   styleUrls: ['./login.component.css']  
  8. })  
  9. export class LoginComponent {  
  10.   username: string;  
  11.   password: string;  
  12.   title = 'auth-guard-demo';  
  13.   constructor(private _auth: AuthenticationService, private _router: Router) {  
  14.     if (this._auth.loggedIn) {  
  15.       this._router.navigate(['home']);  
  16.     }  
  17.   }  
  18.   login(): void {  
  19.     if (this.username != '' && this.password != '') {  
  20.       if (this._auth.login(this.username, this.password)) {  
  21.         this._router.navigate(["home"]);  
  22.       }  
  23.       else  
  24.         alert("Wrong username or password");  
  25.     }  
  26.   }  

Code for login.component.html file.
  1. <div class="container">    
  2.   <div class="row">    
  3.     <div class="form-group col-md-12">    
  4.       <label>Username</label>    
  5.       <input type="text" [(ngModel)]="username" name="username" class="form-control" />    
  6.     </div>    
  7.     <div class="form-group col-md-12">    
  8.       <label>Password</label>    
  9.       <input type="password" [(ngModel)]="password" name="password" class="form-control" />    
  10.     </div>    
  11.     <div class="form-group col-md-3">    
  12.       <button (click)="login()" class="btn btn-success">Login</button>    
  13.     </div>    
  14.   </div>    
  15. </div>    
Open the app-routing.module.ts file and add the code in it. 
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { HomeComponent } from './home/home.component';  
  4. import { AuthGuard } from './_service/auth-guard.service';  
  5. import { LoginComponent } from './login/login.component';  
  6. const routes: Routes = [  
  7.   {  
  8.     path: 'home',  
  9.     component: HomeComponent,  
  10.     canActivate: [AuthGuard],  
  11.     data: {  
  12.       title: 'Home'   
  13.     }  
  14.   },  
  15.   {  
  16.     path: 'login',  
  17.     component: LoginComponent,  
  18.     data: {  
  19.       title: 'Login'  
  20.     }  
  21.   },  
  22.   {  
  23.     path: '',  
  24.     component: LoginComponent,  
  25.     data: {  
  26.       title: 'Login'  
  27.     }  
  28.   }  
  29. ];  
  30. @NgModule({  
  31.   imports: [RouterModule.forRoot(routes)],  
  32.   exports: [RouterModule]  
  33. })  
  34. export class AppRoutingModule { } 
Code for app.component.ts file. 
  1. <router-outlet></router-outlet> 
Place the dependencies in app.module.ts file. 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { AuthenticationService } from './_service/authentication.service';  
  7. import { HomeComponent } from './home/home.component';  
  8. import { LoginComponent } from './login/login.component';  
  9. @NgModule({  
  10.   declarations: [  
  11.     AppComponent,  
  12.     HomeComponent,  
  13.     LoginComponent  
  14.   ],  
  15.   imports: [  
  16.     BrowserModule,  
  17.     AppRoutingModule,  
  18.     FormsModule,  
  19.   ],  
  20.   providers: [AuthenticationService],  
  21.   bootstrap: [AppComponent]  
  22. })  
  23. export class AppModule { } 
Finally, open the index.html file and add the bootstrap reference in it.
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>AuthGuardDemo</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9.   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    
  10.   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    
  11.   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>    
  12.   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>    
  13. </head>    
  14. <body>    
  15.   <app-root></app-root>    
  16. </body>    
  17. </html>     
Protecting Routes With Auth Guard In Angular 7
 
Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.


Similar Articles