JSON WEB Authentication with Angular 8 and NodeJS

JSON WEB Authentication with Angular 8 and NodeJS

JSON WEB Authentication with Angular 8 and NodeJS

The article is about interfacing an Angular 8 Project with a secure backend API. The Backend will be running on Node.JS. The security that will underlay the interfacing will be JSON Web Tokens.

At the end of the article, you should have learned to;

  • Create JSON Web Token after Authentication
  • Secure API Endpoints with JSON Web Tokens
  • Integrate JSON Web Tokens in Angular 8
  • Store and Retrieve a JSON Web Token
  • Implement an Interceptor/Middleware in Angular 8 and Node.JS
  • Implement a Status 401 Unauthorised Code

What is JSON Web Tokens?

JSON Web Token is an RFC Standard (Request for Comments) https://tools.ietf.org/html/rfc7519. The RFC Standard is a best-practice set of methodologies. It takes in a JSON object and encrypts it using a secret key that you set, HMAC algorithm, or a public/private key pair that can be generated using RSA or ECDSA. For this tutorial, we will be using a secret key.

Why use JSON Web Tokens?

It is a secure way to verify the integrity of the exchange of information between the client and the server. We will adapt it for authorisation so that in case of any breach, the token will not verify or expire based on time.

Why use JSON Web Tokens?

Why use JSON Web Tokens?

Theory in Practice

We will be using Angular on the frontend and a Node.JS server on the backend. On the Angular side of things, an interceptor will be created. An interceptor is a service that will break any HTTP Request sent from Angular, clone it and add a token to it before it is finally sent. On the Node.JS side of things, all requests received will first be broken and cloned. The token will be extracted and verified. In case of successful verification, the request will be sent to its handler to send a response and in the case of an unsuccessful verification, all further requests will be canceled and a 401 Unauthorized status will be sent to Angular. In the interceptor of the Angular App, all requests will be checked for a 401 status and upon receiving such a request, the token stored at Angular will be removed and the user will be logged out of all sessions, sending him to the login screen.

Let’s create the Angular App:

Now let’s create our Interceptor:

Now go to src/app/app.module.ts

We will be importing the HTTP Module for HTTP Calls and making our interceptor as a provider so it has global access to all HTTP Calls.

Now let’s open the interceptor service class:

Now go to src/app/auth-interceptor.service.ts:

Section 1

As in authentication, the token we get from the server will be stored in the local storage, therefore first we retrieve the token from local storage. Then the httpRequest req is cloned and a header of “Authorisation, Bearer: token” is added to it. This token will be sent in the header of the httpRequest. This method can also be used to standardised all the requests with the Content Type and Accept header injection too.

Section 2

In case of an error response or error status such as 401, 402 and so on so forth, the pipe helps to catch the error and further logic to de-authenticate the user due to a bad request (Unauthorised Request) can be implemented here. In the case of other error requests, it simply returns the error in the call to the frontend.

Great, now let’s create the Backend.

Create a Directory for the Server and type in npm init to initialize it as a node project:

Use the following command to install the required libraries:

Let’s create an app.js in the node_server folder and start coding the backend.

Now, this is app.js and the boilerplate code:

Now we need to have a route where the token is generated, usually, in a production app, this route will be where you will be authenticating the user, the login route, once successfully authenticated, you will send the token.

 

So now we have a route, a secret for encoding our data and remember a data object i.e userData. Therefore, once your decode it, you will get back to this object, so storing a password is not a good practice here, maybe just name and id.

Now let’s run the application and check token generated:

We will be using postman to test our routes, great tool, I must say.

Token generation

Token generation

As you can see, we have successfully generated our first web token.

To illustrate a use case, we have just created a path1 and I want to secure this endpoint using my JSON Web Token. For this, I am going to use express-jwt.

Express-JWT in motion.

To further illustrate the code, it states that only allow these paths to access the endpoint without token authentication.

Now in the next step, we will try to access the path without a token sent in the header.

Accessing the path without a token

Accessing the path without a token

As you can see, it didn’t allow us to access the path. It also sent back a 401 Unauthorized, so that’s great. Now let’s test it with the token we obtained from the token/sign route.

As you can see, when adding the Bearer Token, we have successfully gotten access to it. Heading back to angular, I just created a new component home

Now this is my home.component.ts file

So simply, on the signIn function, I am requesting a token and storing it into localstorage and then on the second function, I am requesting the path.

JSON Web Test

JSON Web Test

Now when I run the application, this is a response, I am expecting. Now I am going to refresh, so I can lose the localstorage token, and then try to access the path.

Last step: secure app

Last step: secure app

As you can see, we have successfully gotten a 401 Unauthorized, therefore our application is secured.

Conclusion

We have successfully secured our service and all communication between the two parties using JSON Web Tokens. This article has helped us in taking an overview of implementing the JWT in both Angular 8 and Node.JS. I hope this contribution will help you in securing your applications and taking a step towards making it production-ready.

GitHub: https://github.com/th3n00bc0d3r/Json-Web-Token-Authentication-with-Angular-8-and-Node-JS

 

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

15.03.2024

JAMstack Architecture with Next.js

The Jamstack architecture, a term coined by Mathias Biilmann, the co-founder of Netlify, encompasses a set of structural practices that rely on ...

19.01.2024

Training DALL·E on Custom Datasets: A Practical Guide

The adaptability of DALL·E across diverse datasets is it’s key strength and that’s where DALL·E’s neural network design stands out for its ...

12.06.2023

The Ultimate Guide to Pip

Developers may quickly and easily install Python packages from the Python Package Index (PyPI) and other package indexes by using Pip. Pip ...

1 comment

Nikita Bragin March 26, 2020 at 10:44 am
0

A question from Reddit:

why did you clone the request three times?
`

req = req.clone({ headers: req.headers.set(‘Authorization’, ‘Bearer ‘ + token) });

req = req.clone({ headers: req.headers.set(‘Content-Type’, ‘application/json’) });

req = req.clone({ headers: req.headers.set(‘Accept’, ‘application/json’) });

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy