Securing routes using route guards

When you sign out of the application and manually go to the sales URL in the browser, you will still see that the user is able to navigate to the Sales page without being authenticated. This is a potential security issue since the unauthenticated user is able to navigate to a page that they aren't authorized to view.

Guarding routes is very important for the security of our applications. We want to make sure that only the users who are allowed to view the page are able to access the page. In our case, we want our Sales page to only be viewed by authenticated users. Angular provides a way to guard the routes using Angular guards. For that, we need to create a service and implement CanActivate from Angular router and implement the canActivate method, which returns a Boolean or an observable of a Boolean. If the return value results in true, then a user can see the page, otherwise, they won't be able to view it. Let's use store.select to know if the user is authenticated or not from the store. If the user is authenticated, return true; otherwise, navigate to the Home page and return false.

Let's create AuthGuard using the following Angular CLI command:

> ng g guard auth --project es-admin

Let's update the guard to use our store, using the following code:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { AUTH_FEATURE_KEY } from '@ngprojects/auth/src';
import { map } from 'rxjs/operators'
;

@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {

constructor(private store: Store<any>, private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(state => state[AUTH_FEATURE_KEY].authenticated).pipe(
map(authenticated => {
if (authenticated) {
return true;
} else {
this.router.navigate(['home']);
return false;
}
}),
);
}
}

Now, let's use our AuthGuard to guard our sales route, using canActivate for the route, as follows:

import { AuthGuard } from './auth.guard';

@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[
...
{
path: 'sales',
loadChildren: () => import('./sales/sales.module').then(mod
=> mod.SalesModule),
canActivate: [AuthGuard] }
],
{ initialNavigation: 'enabled' }
),
...
],
...
})
export class AppModule {}

Now, when you click on the Sales link in the navigation, you should see that it does not navigate to the Sales page, instead remaining on the Home page because of our Auth guard.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.147.215