Skip to content
Related Articles

Related Articles

Improve Article

Auth Guards in Angular 9/10/11

  • Last Updated : 19 Jul, 2021
Geek Week

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 unauthorised 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-authorised access in AngularJS.




My Personal Notes arrow_drop_up
Recommended Articles
Page :