Guarding routes
Since we've already implemented auth, we'll need to protect the application's routes from non-authenticated users.
Not all pages should be protected; for example, the user's profile page could be made public so that users who do not yet have an account can find other users via search engines. If they have friends on the network, this will encourage them to sign up for an account.
Let's begin by creating an auth guard, as follows:
- Return to your Terminal and type the following command:
ng g guard core/guards/auth/auth
You'll be prompted with Which interfaces would you like to implement?
.
Press spacebar to select CanActivate
, then Enter to confirm.
- Open the
core/guards/auth/auth.guard.ts
file and start by importing the auth service andRouter
, like this:import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router'; import { AuthService } from ...