Auth Guard (JWT) in Angular

In the previous post I showed how to manage a token in an angular application. Now I show you how you can use the Auth Guard mechanism so that you can not go on specific components  without authentication on the SPA application side.

Example

At first let’s create auth guard service by use command ng g guard auth. After my modification it’s look like below.

What I did was injected auth service which will validate the correctness of the token. And returns information about whether something can be activated or not and additionally displayed information in the console about whether someone can be here or not.

Next create two components (named “private” and “home) and call them using the buttons that put in the main view.

Let’s look at routing now.

Looks normal (more about routing here) but add the case that only a person with a token can go to the private view.

To do that you can add a canActivate attribute to a specific routing with a reference to our auth guard and it looks like this.

But if we have many such cases that we want to use canActivate and we want to follow the DRY rule then we can use such a code.

More about routes here.

Entire auth guard.

And it looks as follows.

Whole code on github.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *