Authguard Angular Authentication Using Route Guards In Angular 11


In this article, you will learn how to create auth guard in angular 11. some time protect URL then use Guard, so this time learn implementation of Authguard in Angular 11.

In this tutorial, we will learn that if a user is logged in only then he should not go to the dashboard or any other page, then he should go to the login page again as you would have seen on any other website Or we want to stop the user on any page of our website which does not go to him, only the person whom we authorize goes to that URL, we also use the angular auth guard to stop it, which we will see below

Auth guard implementation in angular 11 To complete this program we will use canactivate angular auth guard. We can use a route guard in Angular using these simple steps:

Authguard Angular Authentication Using Route Guards In Angular 11

Step 1 - Create an angular app

First of all, create a new angular app "ng new angularauthguard". Let's create an angular app using the following commands.

ng new angularauthguard


Step 2 - Create a Guard

Let's open your created app. Create Authguard with the following command: auth is a folder name.

ng g guard auth/login


To create an Angular guard, you need to select the CanActivate.

Authguard Angular Authentication Using Route Guards In Angular 11

Step 3 - Create a login

In this step we will create simple login, we will change the login page to open the login.component.ts file which can now be seen below. we use localStorage.setItem this we want to store what we want to store in our localstorage, we can use it, we will log in

login.component.html

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

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

  constructor() { }
  userid = '1';
  ngOnInit(): void {
    localStorage.setItem('session', this.userid)
  }

}

Step 4 - Write a login guard code

Open the login.guard.ts file and change the code to what is given below:

auth/login.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {
  constructor( private routes: Router){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
      if (localStorage.getItem('session') != null) {
        return true;
      }
      else {
        this.routes.navigate(['/login']);
        return false;
      }
  }
  
}

Step 5 - Create a route

Use canActivate property of the Route interface to guard the route, for example, AuthGuard. Now find the canActivate property used in route declarations.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { QRCodeModule } from 'angularx-qrcode';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginGuard } from './auth/login.guard'; // -------- import this guard----

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    QRCodeModule
  ],
  providers: [ LoginGuard],     //---------- Update this code and import
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

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

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

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

Conclusion

In this tutorial, we used an authguard. In this tutorial, we learned how we cannot access a URL until a user is logged in. auth guard implementation in angular 11. It automatically redirects to the login.


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close