Auth Guards in Angular 9/10/11 - GeeksforGeeks

03 Nov, 2021
AuthGuard is used to protect the routes from unauthorized access in angular.
How AuthGuard Works?
Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor. It will be called before accessing the routes. The canActivate has to return true to access the page. If it returns false, we can not access the page. We can write our user authorization and authentication logic inside the canActivate function.
AuthGuard is used to protect the routes from unauthorized access
So here we are creating an AuthGuard in angular that will protect our routes from unauthorized access.
Example: We can create an AuthGuard by running simple command using CLI.
ng g guard services/auth
The above command creates the AuthGuard inside the services folder and the AuthGuard name is auth.
auth.guards.ts
import { Injectable } from "@angular/core";import {    ActivatedRouteSnapshot,    CanActivate,    Router,    RouterStateSnapshot,    UrlTree} from "@angular/router";import { AuthService } from "./auth.service";  @Injectable()export class AuthGuard implements CanActivate {    constructor(        private authService: AuthService,        private router: Router) { }    canActivate(        route: ActivatedRouteSnapshot,        state: RouterStateSnapshot): boolean | Promise<boolean> {        var isAuthenticated = this.authService.getAuthStatus();        if (!isAuthenticated) {            this.router.navigate(['/login']);        }        return isAuthenticated;    }}
Inside the canActivate function, we are checking whether the user is authenticated or not and “getAuthStatus” method returns a boolean value. So based on this value we return the value from canActivate method. If the “getAuthStatus” return value means user is authenticated then we allow the user to access the page otherwise we navigate the user to the login page.
Then we have to update our routing file so which route is protected by AuthGuard and which route is accessible for every user.
app-routing.module.ts
import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AuthGuard } from './services/auth.guards';import { LoginComponent } from './auth/login/login.component';import { SignupComponent } from './auth/signup/signup.component';import { PostCreateComponent } from './posts/post-create/post-create.component';import { PostListComponent } from './posts/post-list/post-list.component';  const routes: Routes = [  { path: '',   component: PostListComponent },  { path: 'create',   component: PostCreateComponent,   canActivate: [AuthGuard]},  { path: 'edit',   component: PostCreateComponent,   canActivate: [AuthGuard] },  { path: 'login',   component: LoginComponent },  { path: 'signup',   component: SignupComponent }];  @NgModule({  imports: [RouterModule.forRoot(routes)],  exports: [RouterModule],  providers: [AuthGuard]})  export class AppRoutingModule { }
Here inside the routes array, we have provided the canActivate: [AuthGuard] to “create” and “edit” routes so these two routes are only accessible to authenticated users and other routes are open for all users.
{ path: ‘create’, component: PostCreateComponent, canActivate: [AuthGuard]},{ path: ‘edit’, component: PostCreateComponent, canActivate: [AuthGuard] },
Make sure to import AuthGuard in this routing file and also add it inside @NgModule providers.
@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule],providers: [AuthGuard]})
So that’s how we can protect routes from un-authorized access in AngularJS.
chhabradhanvi
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills