Using JWT as Authentication in API Gateway

JWT logo

This is the last part of our journey to build simple microservice. Now we will give an authentication module to make our APIs secure.

What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

  • Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed — for example, using public/private key pairs — you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.

You can read more about JWT, next what we will do is:
- Setup .env
- Create middleware
- Add middleware to route
- Run in Postman

Setup .env

The important variables for me is the Token Secret and Token Lifetime, in this tutorial we only use access token. But you can add the refresh token as well.

.env JWT variables

Create Middleware

Middleware is a request gateway, it will make our request allowed to the controller or not. So we will create veriftToken.js file inside middleware folder. Of course don’t forget to install JWT.

middleware folder

in verifyToken.js, we will check the token from Authentication header is valid or not.


Add Middleware to Routes

To use the middleware in route is very easy. We only need to require the verifyToken.js, and put it in second params of routes. Example, this route is required header named Authentication with JWT token. If token is valid, the client will get detail of user.

users.js routes

Run in Postman

In this project, we can get the JWT token by login api.

login api

And then we will try to access routes with middleware, it should be can not accessed without token.

error token

Next, we will try access that route with token. It should be return success API.

success reponse

So that is how to implement JWT in API Gateway Microservice. We can secure the private API by the JWT token. For you that need the project can visit my Github. And of course can follow previous step start from here.