JWT Tokens with Node.js and Express


In this example I show how to create access tokens for an application using Node.js and express. JSON Web Tokens are a standard type of token that is used widely to certify user identity by a server before sending data back to the client machine.

First I sign JWT with a secret token from the client. Then the server verifies the token and reads the information if the token is valid. I also created the ability to have the tokens expire or be refreshed as is needed. 

For the initial setup I just needed to make sure Node.js and express were installed and up to date. Then I added a package called nodemon to monitor for any changes and to react accordingly. To handle the authentication in a secure manner I also created a separate server for handling the main request and one that is used purely for authentication.


Additionally, in a rest file I am creating the parameters for the /posts and /login requests. The application type is json hence the name JSON Web Tokens.


The initial test to the server returns a 200 code along with the "accessToken" so I know everything is working up to this point. The access tokens are being generated.


I next modified the code to return a refresh token so that the initial token can be expired and I can give users new tokens to continue to verify user identity but I don't just have one token that can be used over and over. This is for safety too, because it helps me lock the server in essence every time a token expires.


Ok, so now that I have tokens and refresh tokens generating, I need to use those to access data. I now am getting back specific user data based on their token. Here the first post is returned for the username "Jason".


Here below you can see that a token will expire and eventually the server is locked again. Any additional requests will return a "403 Forbidden" error.



This process is actually only part of the equation. JWT tokens are used in tandem for additional security with user passwords. It is in interesting process because it allows granular control of user access to server data in a way which access can be granted, extended or restricted in an accurate and efficient manner.


Comments

Popular posts from this blog

Automated Exploitation of a Bluetooth vulnerability that leads to 0-click code execution

Sniffing GSM traffic on a private cellphone network

Raspberry Pi WiFi Honeypot 🍯