Route Guards

We will use route guards to restrict access to pages that should only be viewed by authenticated users. We imported and used our generated route guard files when we set up our app's routing. However, the route guards generated by the CLI always return true, meaning everyone always has access to them.

Let's change that now.

Note: It's important to note that route guards alone do not confer sufficient security. A client app is, by nature, public. Angular provides ways to restrict views and abstain from loading data for unauthorized users, but we must always ensure that our API backend is secured properly.

Authentication Guard

Open the auth.guard.ts file:

// src/app/auth/auth.guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';

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

  constructor(private auth: AuthService) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (this.auth.isAuthenticated) {
      return true;
    }
    // Save secure path to redirect to after
    // successful login and prompt to log in
    this.auth.storeAuthRedirect(state.url);
    this.auth.login(true);
    return false;
  }

}

The Auth guard uses the canActivate interface (as we saw in our app routing) to activate the requested route if conditions are met (in this case, if the isAuthenticated method returns true). If conditions are not met, the user is prompted to log in, and the guarded URL is passed to the login() method so that the user can be redirected to this route once they're authenticated.

results matching ""

    No results matching ""