JWT Bearer token authentication for Express JS via Middlewears and Request-Response pipeline.

Express API s with JWT Auth

Dinuwan Kalubowila
MS Club of SLIIT
Published in
7 min readMar 21, 2020

--

Pre-Requirements

REST API handling with Express JS

Why Authentication in REST API’s ?

In either MERN or MEAN stack development, usually, we integrate our REST API s using Express JS. Maybe POST, GET, PUT and DELETE requests are there. When developing a backend to the enterprise level web application, we have authenticated some required routes. Simply we put some restrictions to access to user route according to the user levels. For the authenticate purpose JavaScript developers typically use JSON Web Tokens(JWT).

This is the story that binds with JWT and ExpressJS.

How it actually works?

You can do this authentication either synchronously or asynchronously. If you visit the above GitHub repository you can get the documentation of JWT. If synchronously, you can set a variable to the JWT sign method and pass it into the payload with the secret key. Asynchronously, you have to use a callback function for this purpose.

You can require the above-installed node module of JSON Web Token using the require statement. The bellow picture shows the current coding that you should have.

Inline 16–20 in the above code block, It generates an authorization key according to the logged user in the above scenario.

Inline 16–20 in the above code block, It generates an authorization key according to the logged user in the above scenario. I use here asynchronous approach to do it. How id does that, accept the above hard-coded user object with relevant details as 1st parameter. As a 2nd parameter, you have to pass some string value. simply a secret key that you prefer. In the 3rd parameter, the sign function calls the callback function to generate the authentication token. If you got any errors,you can print it also.Otherwise, the secret key will be displayed as bellow.

How to authenticate those routes? Therefore before developing any kind of REST API, you should have to understand how requests and responses will be going to control. For that purpose, you need to identify the Request-Response pipeline.

What is a Request-Response Pipeline?

First I don’ say anything :D . Try to get some understanding by only watching the above picture.

As an example, if you are not logged into your Facebook account,you will not be able to change your passwords, If you have not logged in to an E-Commerce app, the application does not allow to add products into the cart without a valid login. Before login, you should have a user account. Otherwise, user neither accesses to the profile nor add products into cart in the above E-Commerce site example. How did these things happen in REST API?

This is the place that the Request-Response pipeline is involving. It validates the user request step by step. So we call those steps as middlewares.

As the above picture once a request is created it appears to the Middleware 01. If the condition on the middleware 01 is approved, the particular request passes to the 2nd middleware. Unless the request passes to the upcoming middlewares, the request is lost. Neither forwarding the request anymore nor executing at the same positions. That is why we are getting some Forbidden messages sometimes. (403 requests).

When responding to a request the same procedure is happening, but reverse order. The response will trigger middleware 03 first, then 2 and 1.

This is the abstract execution behind the middlewares and request-responses pipelines.

As an example even if there is a logged user in an E-Commerce application, every user not allows the admin features. Only admin can access those admin features. Then how can application differentiate whether the logged user either administrator or not?. Do developers need to separate login portals? No.It needs only one login.but when generating the JWT token when the login process,it is a unique one. That token embedded whether the logged user either admin or not. How REST API track that scenario? Completely checking the above middlewares through the request-response pipeline. Even single middleware validation will fail, the entire request is going to lose.

So now we are going to implement a specific middleware for the login authentication.

According to the above picture, you have to implement the verifyToken method as your middleware function. Simply those middlewares are function. Either they will return something to the endpoint or execution reference to the next middleware function.

In the above function is for validation purposes. You already know what is the req, res words are. So what is ‘next’.It implies the next middleware function that has to be executed.

So in the above get request, it gets a executable reference from verifyToken middleware function. The verifyToken function is going to execute from here. After executing the verify token middleware next() command is ready to execute another middleware next to the verifyToken. But in the get request, I did not attach another executable reference to the 2nd middleware to be called. If you want to attach another middleware authentication you can implement a separate method and add it’s a reference to the get request’s pipeline as bellow.

app.get(‘/api/login’,verifyToken,<midlw 02>…<midlw 03>,(req,res))

Let’s move on to the postman testing for this scenario now. At last, we can discuss the body part of the verifyToken method.

To access the profile user have to login first. At the login, the user will get a secret token key as previously. So you can copy that token and paste it like above.

If you do not attach the secret token into here, you might not be allowed to access the profile. You might get the Forbidden message.

If there is a valid token in Authorization, logged user can get the details embedded inside the token. Why you get all user details here? Because you have already passed the entire user object into jwt.sign() function.(See the 16th line of 1st picture)

So how those Headers keys came?. Why we put our token as ‘Bearer <token>’?Lets’s move on to previous image that we temporarily skipped. :D

Implementation of the verifyToken() method

To access the profile user have to login first. At the login, the user will get a secret token key as previously. So you can copy that token and paste it like above.

If you do not attach the secret token into here, you might not be allowed to access the profile. You might get the Forbidden message.

If there is a valid token in Authorization, logged user can get the details embedded inside the token. Why you get all user details here? Because you have already passed the entire user object into jwt.sign() function.(See the 16th line of 1st picture)

So how those Headers keys came?. Why we put our token as ‘Bearer <token>’?Lets’s move on to the previous image that we temporarily skipped. :D

Let’s move to the body of the verifyToken function. It requests something on header. Simply it is requesting the ‘Bearer <>’ string that we paste from login. Either Angular or React you will be passing this to your local storage.In the postman our key is the ‘Authorization’ value of the key is ‘Bearer <>’ string.The root topic of the ‘Authorization’ key is ‘Header’.

At the 41 st line in one before the last picture, ‘bearerHeader’ variable assigns the string in the ‘Authorization’ keyword under the Header part. That is why it says ‘req.headers’.

After you get the token, the application will check either if there is token available or not or if available, check the validity of the token. The entire process is happing on single line.’undefined’ the key is responsible for the availability and validity of the token. Otherwise else part executed and send the Forbidden message. Then the request will be going to lose.

In the above case, it takes enter string (Bearer<>). So we have to splice above string to array elements. We split the space between Bearer and token value. Then in line 45 we take the 2nd element of the array to the separate variable. Thereafter our token of the ‘req’ parameter will assign the above element.(2nd array index).

Then it passes to the next middleware. In this example as we discuss earlier there is no any middlewares more, it will be accessed the request in the out get method. And also passes it t as a parameter to the callback function.

So if there is no error, JSON object with logged user’s data will receive.

It is long story so far.Anyway this is how JWT authentication,Middlewaers and Request-Response Pipeline works inside Express REST API.

Get source code from here.

--

--

Dinuwan Kalubowila
MS Club of SLIIT

Software Engineer at WSO2 | Ex Gold Level Microsoft Learn Student Ambassador