NashTech Insights

Auth Guard In Angular

Piyush Agrawal
Piyush Agrawal
Table of Contents
Route Gurad

Authentication is a very essential part of every application. Without authentication, we can not protect our data. Angular provide us an nice feature that help us to protect our data or we can say protect our routes. In this blog we are going to learn how can we implement Auth Guard in our angular application and protect our routes.

Prerequested:

Basic knowledge of Angular Routing

To implement Auth gurad in angular follow below steps.

Setting Up an Angular Application

Before diving into Auth gurad , first create Angular Application

Step 1

Run command for create Angular App

ng  new  angular-auth-guard-implementaion

Step 2

After creating Angular Application, Let’s create Basic Component

So First we create a Login Page and where we have 2 fields Email and Password.

For creating login page run command

ng generate  component login/user-login 

Inside your component create login Form And Store data in Local Storage

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

import { FormControl, FormGroup, Validators } from '@angular/forms';

import { Router } from '@angular/router';

@Component({

  selector: 'app-user-login',

  template: `<form [formGroup]="loginForm" (ngSubmit)="login()" >

                <label for="email">Email</label>

                <input class="form-control" formControlName="email" type="email" />

                <label for="password">Passwerd</label>

                <input class="form-control"  formControlName="password" type="password" />

                <button class="btn btn-success" type="submit">Submit</button>

              </form>`,
})
export class UserLoginComponent {

  constructor(private router: Router){}

  loginForm = new FormGroup({

    'email': new FormControl('', Validators.required),

    'password':new FormControl('', Validators.required),

  })


  login(){

    if(this.loginForm.valid){

      localStorage.setItem('login', JSON.stringify(this.loginForm.value));

      this.router.navigate(['/', 'home'])

    }

  }

}

In the above code we have create a sample form and we are saving form value in localStorage.

We will use the stored detail for authentication.

So let’s create Home Component

Simply run command

ng generate component home

Now Home Component created.

Step 3

Let’s Steup routing so open app-routing.module.ts file and set below code.

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

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';

import { UserLoginComponent } from './login/user-login/user-login.component';

const routes: Routes = [

  { path: '', redirectTo : 'login' , pathMatch: 'full'},

  { path:'login', component: UserLoginComponent },

  { path: 'home', component: HomeComponent}

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

In the above code, we have implemented a routing in our Applictaion.

Let’s compile and run the and check browser. Now you will redirect to login page and check URL of your application.

if you change /login to /home the you will redirecting to Home page.

Now Whats wrong with our Application. Without login detail How are we navigating?

confused

Basically, we didn’t added any validation in our application.

Step 4

Let’s implement Auth Guard.

Run command

ng generate guard user-auth

user-auth.gurad.ts file created with this logic.

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

import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';

import { Observable } from 'rxjs';

@Injectable({

  providedIn: 'root'

})
export class UserAuthGuard implements CanActivate {

  canActivate(

    route: ActivatedRouteSnapshot,

    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    return true;

  }
  
}

Let’s add our logic for Authentication


@Injectable({

  providedIn: 'root'

})
export class UserAuthGuard implements CanActivate {

  canActivate(

    route: ActivatedRouteSnapshot,

    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

      let loginDetails = JSON.parse(localStorage.getItem('login') || '');

      if(loginDetails.email && loginDetails.password){

        return true;

      }

    return false;
  }
  
}

Now we have added all the logic for validate route.

Let’s use UserAuthGuard in our app-routing.module.ts file.

Step 5

Add UserAuthGuard in app-routing.module.ts file.

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

import { RouterModule, Routes } from '@angular/router';

import { UserLoginComponent } from './login/user-login/user-login.component';

import { HomeComponent } from './home/home.component';

import { UserAuthGuard } from './user-auth.guard';


const routes: Routes = [

  { path: '', redirectTo : 'login' , pathMatch: 'full'},

  { path:'login', component: UserLoginComponent },

  { path: 'home', component: HomeComponent , canActivate: [UserAuthGuard]}
];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Now all things are setup, again compile your application and visit browser.

Now same you will redirect to login page and if your try to visit home then you will not be able to see home page without login.

Lets do login and you will easily navigated to home page after filling form and click on submit button.

enjoy

We have implemented AUth Gurad Successfully.

Conclusion

Authentication is very important in every application. By Using Auth Gaurd you can easily protect your route. By following the steps outlined in this blog post and utilizing Angular’s Auth Guard , you can easily manage authentication. Enhance your Angular Application security and provide a seamless user experience.

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: