guard basic auth code example

Example 1: auth guard

// src/app/auth/auth-guard.service.tsimport { Injectable } from '@angular/core';import { Router, CanActivate } from '@angular/router';import { AuthService } from './auth.service';@Injectable()export class AuthGuardService implements CanActivate {  constructor(public auth: AuthService, public router: Router) {}  canActivate(): boolean {    if (!this.auth.isAuthenticated()) {      this.router.navigate(['login']);      return false;    }    return true;  }}

Example 2: auth guard

// src/app/auth/auth.service.tsimport { Injectable } from '@angular/core';import { JwtHelperService } from '@auth0/angular-jwt';@Injectable()export class AuthService {  constructor(public jwtHelper: JwtHelperService) {}  // ...  public isAuthenticated(): boolean {    const token = localStorage.getItem('token');    // Check whether the token is expired and return    // true or false    return !this.jwtHelper.isTokenExpired(token);  }}

Tags:

Misc Example