How To Add Authguard Service In Angular 5

Posted By Shilpa Adlakha | 30-Apr-2018

The Angular application can be guarded using authguard service which allows to grant or restrict access to certain URL of the application.The main purpose of authguard service is to not to allow to directly hit URL without logged into the application we use authguard service.

 

There may be scenarios on the basis of which we restrict the user to navigate into the application, it may be the user must login (authenticate) first or may be the user has logged in but is not authorized to navigate to the particular component.

 

We have four different types of Guards:

 

can activate: it is used to check whether a user can visit a route.

 

CanActivateChild: it is used to check whether a user can visit a routes children.

 

can deactivate: it is used to check whether a user-user can exit a route.

 

Resolve: it is used to perform the route data retrieval before the route is activated.

 

CanLoad: it is used to see if a user can route to a module that lazy loaded.


To implement authguard service we use a CanActivate method, these are created as @Injectable classes.this return either true if the user can access a route or false if they can’t.


It can be used to return an observable or promise with API integration, This will keep the user waiting until the guard returns true or false.

 

Lets create a simple CanActivate guard.

 

First we need to import the CanActivate interface,:

import { CanActivate } from "@angular/router";

Then lets create an Injectable class called AppAuthGuard which implements the canActivate function:

AppAuthGuard implements CanActivate {
  canActivate() {
    console.log("AppAuthGuard");
    return true;
  }
}

Now we declare this created service in the providers section of ngmodule

@NgModule({
  providers: [
    AppAuthGuard
  ]
})

Now in next step, we will add this authguard service to specific routes which we want to restrict user without permission

const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'find', redirectTo: 'search'},
  {path: 'home', component: HomeComponent},
  {path: 'about', component: AboutComponent},
  {
    path: 'about',
    component: AppAuthGuard,
    canActivate: [AppAuthGuard],
  },
  {path: '**', component: HomeComponent}
];

We have added our AppAuthGuard to the list of canActivate guards for this route to restrict the user to hit direct URL without permission

Thanks!

Request for Proposal

Recaptcha is required.

Sending message..