Guards in Angular

Photo by Mitchell Ng Liang an on Unsplash
Share this

Is the first line of defense, you can protect routes easily and very effective, based on the boolean of “this token is valid”. 

When we get the token from the Login-service that we saw in our previous post, we know when it will expire. So for that, we can use an authentication service which checks whether or not the user is authenticated, for that we will use the HwtHelperService class from angular2-jwt

$ npm i --save angular2-jwt

And in our authentication service, we import it and declare it in the constructor. 

import { JwtHelperService } from '@auth0/angular-jwt';
constructor(public jwtHelper: JwtHelperService) { }

  public getToken(): string {
    const token = localStorage.getItem('token');
    return JSON.parse(token);
  public isAuthenticated(): boolean {
  	const token = this.getToken();
  	return !this.jwtHelper.isTokenExpired(token);

I use the json.parse after getting it from the local storage, to “clean” it a little. Then call a clean token in my isAuthenticated() function, that returns me a boolean, true or false. Now, I need to call this function from my guard and take pertinent actions. 

  constructor(public auth: AuthService, public router: Router) {}

  canActivate(): boolean {
  	if (!this.auth.isAuthenticated()){
  		return false;
  	return true;

In the constructor, I declare my AuthService for calling it later, and also the Router, for redirect the user to the /login. The canActivate() is a method from my guard that will return me a boolean. I will use that boolean, true or false, in my router.

const routes: Routes = [
  { path: '', component: UserlistComponent, canActivate: [GuardService] },
  { path: 'login', component: UserloginComponent},
  //Home sweet home:
  { path: '**', redirectTo: '' }

This method is very effective, but have a problem, oh well a problem with a solution. Now we are validating if the token is expired or no, we can set up the life of our token easily in Drupal, but the idea is not to set a long period of time, that is not secure. So, if we want the guard to let us in, the best solution is to “call” the refresh token service here and update our token and make the validation with this new token. 

Now the question is if we really need the guard in our angular project?. It could be very effective if we use other validations than the expiration time from the token, like for example, if the user has paid a membership or no.

In this example, I will protect my content from the server, we will see that in our last post, Intercept and refresh token in angular for Drupal 8. 

Before that, let’s proceed with a simple post, Adding authorization token in the Angular Header for Drupal 8 Forbidden content. There are two ways, one is directly in the post method, and the other one, more effective is with an interceptor. See You later!. 


Submitted by Developper Thu, 05/31/2018 - 12:28


I'm using Angular 5.

After installing npm i --save angular2-jwt, I get a lot of warnings in my terminal .

in addition of this error :./src/app/services/auth.service.ts
Module not found: Error: Can't resolve '@auth0/angular-jwt'

This line is underlined : import { JwtHelperService } from '@auth0/angular-jwt';

Submitted by Developper Fri, 06/01/2018 - 12:28

These are steps that I followed to have eventually no errors:

for angular 5 version

$ npm i @auth0/angular-jwt v1 

I did an upgrade for the core version as indicated in a warning (I unchecked the mode readOnly from my node_modules repository to allow that)

I changed the module reference in : node_modules\@auth0\angular-jwt\src\jwt.interceptor.d.ts file from:

import { Observable } from 'rxjs/internal/Observable'; 


import { Observable } from 'rxjs/observable'; 

and I changed the module reference in : node_modules\@auth0\angular-jwt\src\jwt.interceptor.js from:

import { from } from "rxjs/internal/observable/from"; 


import { from } from "rxjs/internal/observable/from"; 

Hope that helps someone having the same issue!

Add new comment

The content of this field is kept private and will not be shown publicly.

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.