5.2: Adding Router Guards

Right now anyone can access the members page (and any other site on our application) by typing in the url in their browser.

We need to protect these routes - and, for this we'll use a guard.

Adding Guards

We'll use the Angular CLI to generate auth.guard.ts:

ng g guard guards/auth --no-spec

In the auth.guard.ts file generated, update it to the following:

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private _authService: AuthService,
    private _router: Router) {}

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (this._authService.loggedIn()) {
      return true;
    }

    console.log('You need to be logged in to access that.');
    this._router.navigate(['/home']);
    return false;
  }
}

Add the AuthGuard as a service

In app.module.ts, add AuthGuard to the providers array (and make sure it's imported at the top):

import { AuthGuard } from './guards/auth.guard';
//  ...
providers: [
    AuthService,
    AuthGuard
  ],
//  ...

Adding AuthGuard to the Routes

We have a couple of different options here. We could add a guard to each component.

ex.

{ path: 'members', component: MemberListComponent, canActivate: [AuthGuard] },

But, since all of our routes will have the same guard, this is a bit repetitive.

Perhaps a better method is to create a 'dummy route' - an empty route - and set all of our components we want to use this guard as its children.

Update routes.ts to:

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    {
        path: '',
        runGuardsAndResolvers: 'always',
        canActivate: [AuthGuard],
        children: [
            { path: 'members', component: MemberListComponent },
            { path: 'messages', component: MessagesComponent },
            { path: 'followers', component: FollowersComponent },
        ]
    },
    { path: '**', redirectTo: 'home', pathMatch: 'full' },
];

As we add more guards to our routes - it will be a lot cleaner to do it as in the example above.

Now all of our routes are protected.

Open your browser and verify that it is working as expected.

Last updated