Authentication Using JSON Web Token

Ayush S Bhatt
Apsolutio
Published in
6 min readJun 29, 2020

Welcome to the programming world where you find multiple ways of performing a task. Take User Authentication, for instance. One of the ways is using JSON Web Token. It is stateless which means there’s no need to manage sessions. It is portable and does not require Cookie management which also makes it Mobile-Friendly. Here, in this article, I will introduce the basics of JSON Web Token and a quick tutorial on how to implement them in our project. Have fun!

What is a JSON Web Token?

Formally, it is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties.

The contained information is trusted as it is digitally signed.

The token contains information about the user and transferring it will do the job of accessing private routes.

Why use JSON Web Tokens?

  • Authorization: The authenticated user can access private routes, services and resources permitted for that token.
  • Information Exchange: JSON Web Tokens help in secure transmission of information between two parties. The identity of the sender can be verified as they are signed.

Structure of a JSON Web Token

The JSON Web Token consists of three parts separated by dots (.), namely

  • Header
  • Payload
  • Signature

The Header consists of two parts:

  • Type of token: JSON Web Token and
  • The signing algorithm (HMAC SHA256 or RSA)

The Payload (Base64Url encoded) contains the claims which includes information of the user. It forms the second part of the token.

The Signature contains the encoded header, the payload and a secret.

It restricts tampering of the message.

Putting all of three together and separating each by dots (.), we get the JWT token of the form:

Here’s a sample generated JWT token:

“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWVjYWIzMmJjZWQ5ZTI4OWNmYTQwNjkiLCJpYXQiOjE1OTI4MTIwNTEsImV4cCI6MTU5Mjg0ODA1MX0.Dp5Ahz3YRkDqPFanv6p2GP4Ch7BmAnt7ssiqWdkt4IA”

If you want to checkout the JWT Debugger, here’s a link. Have fun playing with it.

https://jwt.io

How does the JSON Web Token work?

The server returns an access token to the application side after is successful log in.

The application can now use this token to access private or protected routes.

For accessing the private/protected routes, the application should send the JWT in the Authorization header using the Bearer schema. Like so,

Authorization : Bearer <token>

Implementing JWT Authentication in our Project

In our project, we will be using Nodejs express server as our backend.

Firstly, we require NPM packages jsonwebtoken and passport.js by executing the following command in the terminal.

To create the token, we use jsonwebtoken.

Passport.js has various strategies for authentication. Hence, it acts as an authentication middleware for our NodeJs application.

We need to add a few lines in the Node app.js file.

The local strategy uses UserName and Password to authenticate the user. In our project, we’ll be using email and password for authentication.

Let us first configure passport for the local strategy.

We are specifying the usernameField to be our email.

The callback function accepts two parameters namely-

  • username and
  • password (submitted via user login application).

Inside the callback function we have implemented various conditions for authentication using findOne function of mongoose.

It executes when the authenticate function from passport is called.

Adding a POST Route for User Authentication

In our index.js file, we add a post route to take care of User Authentication.

During login, the user will be authenticated against the entered email and password. The generated token is sent to the application.

The Browser’s local storage stores the token. We use this token to access private routes.

As soon as the authenticate function is called, the callback function we created earlier will be fired and will return the parameter using next() which will be required here.

The generateJWT function generates the token upon successful authentication.

Otherwise, it will send an error with its status as the response to the application.

Now, we will define the generateJWT function in our user.model.js file.

In order to create the JWT, we just need to call the sign function from jsonwebtoken.

First parameter is the payload which contains the claims regarding the user, for example: _id representing the unique Object id for a user, generated automatically by MongoDB.

Second parameter is the secret for the encryption of signature part.

SECRET#123 is just an example.

Last part is the token expiration time.

Accessing Private Routes using JWT

In order to access the private routes, the http request must have a valid token.

In the NodeJs server side, we will have to verify the token using jsonwebtoken.

The access to the route will be granted if the token is valid. Let’s create the verifyJWT function.

We will add a new file called JWTHelper.js to define the verification function.

First, we check if the JWT is present in the headers under Authorization type.

The request should contain header in the following format:

Authorization: Bearer <jwt>

Then, we split it using whitespaces and grabbing the 1st index which is the JWT itself and store it in the variable token.

If the token is present, it is verified using the verify function of jsonwebtoken.

Inside the callback function, we will have the decoded payload i.e. the UserID.

The request stores the payload for accessing private routes.

Creating a Private Route

It is time to create a private route so that only the authenticated users can visit it. Suppose, we want to access the User information like name, email, profile picture etc.

Let’s define a GET route to access the user details.

When a GET request is made to the server, the callback function is fired with parameters returned from verifyJWT function.

We use lodash to pick properties (name, email, profile picture etc.) of the user object to be sent as a response to the application side.

These details being user specific needs to be private as it may differ from one person to other.

Hence, we check the JWT to verify the user and send details relevant to the particular user.

That’s it for User Authentication, I hope you learned something from the article.

Checkout Finakya at www.finakya.com!
Apsolutio is at www.apsolutio.com
The Apsolutio blog is at blog.apsolutio.com
Hear what Finakya has to say at blog.finakya.com

--

--