Authentication with Angular and bit of NodeJs

Carlos Zansavio
The Startup
Published in
7 min readJan 12, 2021

Probably there must be a round one thousand of these authentication guides on the internet. But well, I decided to do mine.

I’ll try to focus more on the idea behind an authentication process. If you just want to see the code, please go to the link. More, if you want to real understand what’s going on behind an authentication and try to build it yourself without having looking for this guide twice; please, keep reading.

Authorization and Authentication

Authentication is the act of a user saying who he is.

Authorization is what this person can or not. Can he create a post? Can he see a page?

I’m going to talk about authentication on this guide.

Authentication Methods

There are several authentication methods and JWT (Json Web Token) is one of them. It is a big string that you will need to use in the head of your requests.

So, JWT is just a encoded string like the example in the below:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Inside this weird string we have header, payload (data) and the signature. We can decode this string with any library you want. Just look for jwt decode.

What you have to understand is that inside a JWT token that goes user’s information.

This guide shows a JWT authentication method.

Backend (NodeJs e Loopback)

Before everything, I must say I’m using a server-side framework called LoopBack4 which is maintained by IBM. I like it because it’s Typescript as Angular.

IBM already give us two great classes for authentication-UserService and TokenService. TokenService can verify if a JWT token is valid and also creates new ones. UserService we can test if password is really from user and convert some user data.

A great tutorial can be followed by here. If you follow it, you’ll have a route which receives e-mail, password and returns a JWT token.

Returns

Here is a real token being returned

Now we have our back-end ready. Let’s go to what real matters.

Angular Authentication Implementation

I suggest you to create a mental model of all the steps so you can easily code it.

We want e-mail and password of the user to request back end the JWT token. Then with this token at hands we can store it on the browser. This can be done in several but what I’m going to show you is the localStorage.

It’s important to highlight localStorage is a dictionary (key-value) and won’t expire.

Store values on localStorage

To set a value, you just have to use the setItem like the example in the below

localStorage.setItem(‘myCat’, ‘Tom’);

Fetch values from localStorage

To fetch a value, just use the key

const cat = localStorage.getItem(‘myCat’);

Remove values from localStorage

To remove, just use the key

localStorage.removeItem(‘myCat’);

Cleaning all values

Item clears all the dictionaries from your website.

localStorage.clear();

Now we know how to store this token. Let’s keep moving.

Creating the Authentication Service

Let’s create a user service to authenticate. But first, we have to create a model to represent a JWT token on the system. Go to your project and run this command:

ng generate class models/UserToken

Inside of this class, create a string property called Token, like image in the below:

O repositorio do codigo esta no fim do post

We can focus on UserService and represent this token inside of it. Run this command to create a service:

ng generate service services/user

This command will create a UserService class inside a services folder. This class will be responsible to login, logout users and say to system whose token is.

We will be able to make a class which keeps a system state through Observer pattern. Angular already uses RxJs for this purpose (if you don’t know what I’m talking about, google it).

To use RxJs library we have to create two objects, one private and another public. Private one is which keeps the real state and no one can change it but the UserServices itself. The public is the object which your class clients will use.

Like image in the below:

O repositório do código esta no fim do post

In the constructor we try to get the user token JWT that is stored on browser and assign this value to tokenSubject. If there is no user token, it returns null. And we still have to inject two dependencies: Router and HTTP. The first one is responsible to manage routes inside your application and the second one can make http requests.

Now you should have your foundation ready to create a login method.

We want to create a method that will request the backend the JWT token. So we have to expect e-mail and password in the arguments. After we post this request, we map it for a UserToken (model created before) and set this value in the localStorage. Then we can return it.

O repositório do código esta no fim do post

For logout we have to remove the token from localStorage and notify all listeners. We can also send users to other routes.

O repositório do código esta no fim do post

To make our like easier, we can extract the value from the token subject through a get property.

O repositório do código esta no fim do post

Now all things are set up.

An example on how to use the service

Login Screen

Login screen is the first thing you will want to code. It’s a form with two inputs and one button. When the user submits the forms, one event will rise calling the UserService.login(). Then we make the loading icon appear and if everything succeeds, we send the user to a URL defined before.

O repositório do código esta no fim do post

If it returns an error, loading icon will disappear and probably you want to show the error.

Log-out a user

It’s the same as before. We just call UserService.logout() from where we want to log user out.

O repositório do código esta no fim do post

HTML will be like this:

O repositório do código esta no fim do post

Result

Screen Login

Now we can log out.

Injecting JWT token on the requests

One of the goals to authenticate users is hide routes that he can’t use. For that, you will have to search on your server-side framework how to do it. On LoopBack4, we can decorate the controller we want to hide.

Now this request awaits a JWT token in the header of the requisition.

Middlewares on Angular

Middleware is a pattern which makes easy inject functions before an action occurs.

So for every requests the users make, the JWT token will be injected on the header of the requests.

To create the Interceptor, we can run this command:

ng g interceptor interceptors/Jwt

And the code will be like this:

O repositório do código esta no fim do post

Don’t forget to return the next for other functions to run.

Besides of that, we want to tell the module to use that Interceptor.

O repositório do código esta no fim do post
Inside of app.module.ts

Done. Now every requests is ready to have the JWT Token in the headers.

Final thoughts

It’s important to notice that this authentication system is so easy because Angular implements the dependency injection through a singleton lifetime. We can make the login just once and this state will be on the memory until the end of application (probably when the user closes the browser). When the user returns, it will try to get from localStorage. If it finds, the user is already logged.

This concept is very important to understand as the majority of server-side frameworks I’ve already worked implement dependency injection through transient lifetime.

Another thing we can’t miss is the Observer pattern. I could say that it is just a list of functions that will be executed when the action occurs. When we use RxJs, we want this concept because it’s through that way we can communicate to other components. We can also skip async/await codes through RxJs as the HttpClient library does.

You can see the code here: https://github.com/carloszan/ng-auth-guide

Well, that’s it.

You can send me an e-mail.

--

--

Carlos Zansavio
The Startup

Data Engineer | NLP Researcher | Computer Scientist