Route Guard In Angular :AuthGuard

Introduction

Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve

In this post we will learn canActive topic with example;

Login User Access

If user is logged in then page will navigate otherwise it will route to login page. At first we will add Authguard in routing module .

// src/app/app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import { 
  AuthGuardService as AuthGuard 
} from './auth/auth-guard.service';
export const ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { 
    path: 'profile',
    component: ProfileComponent,
    canActivate: [AuthGuard] 
  },
  { path: '**', redirectTo: '' }
];

In this case we apply Authguard in profile path. For check the user,we will create a file called auth-guard service. This component implements CanActivate method.

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

In here we are checking the user is authenticated or not. In AuthService you can store the login data.

User Role Based Access

In Real time project every role has certain permission, its like admin can see some set of page, user can see only some page, user cant have access admin page.

For this we have to send data with auth guard.

In Routing Module

 {
                path: 'add-member,
                component: AddMemberlComponent,
                canActivate: [AuthGuard],
                data: { module: 'member', action: 'add'}
            }

In AuthGuardService

 const permissionObject = route.data;

From this you can get the data. appPermission is the permission from backend.We have to check and give access.

switch (permissionObject.module) {
      case 'member':
        switch (permissionObject.action) {
          case 'add':
            if (appPermission.member.add == true) {

             return true;
            } else {
              return false;
            }

}
}

Wrapping Up

Hopefully you’ve been able to see the benefits of using Angular’s route guards to help protect access to client-side routes.

Thanks