Node.js JWT Implementation
Hello. In this tutorial, we will implement a Node.js JWT (JSON Web Token) to protect the application endpoints from unauthorized access.
The Node.js framework is commonly used to create server-based applications which are further used to show the contents to the users.
1. Introduction
JSON web tokens (or the JWT’s) is an Open RFC standard that defines a compact and self-contained way for securely transmitting the information from the server to the client. A json web token is usually divided into 3 parts (header, payload, and signature) separated by a dot symbol i.e. [HEADER].[PAYLOAD].[SIGNATURE].
- The header part denotes the crypto operations applied to the token
- The payload part denotes the actual data to be transferred using the token. It also contains information such as issuance time, expiration time, and roles (optional)
- The signature part denotes the verification that the payload wasn’t changed along the way
1.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
2. Node.js JWT implementation
To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Setting up dependencies
Navigate to the project directory and run npm init -y
to create a package.json
file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.
package.json
{ "name": "jwt", "version": "1.0.0", "description": "jwt implementation in nodejs", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "nodejs", "expressjs", "jwt", "restapi" ], "author": "yatbat", "license": "MIT", "dependencies": { "express": "^4.17.1", "jsonwebtoken": "^8.5.1" }, "devDependencies": { "nodemon": "^2.0.12" } }
To download the dependencies navigate to the directory path containing the file and use the npm install
command. If everything goes well the dependencies will be loaded inside the node_modules
folder and you are good to go with the further steps.
2.2 Setting up Express webserver
In the root folder add the following content to the index.js
file. The file will contain the endpoints that will be active once the application is started successfully.
- Creating access token endpoint
- Unprotected endpoint
- The protected endpoint will validate the access token first present in the request header and post validation return the success response. If the access token validation fails forbidden error will be returned to the user
index.js
// importing modules const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); const SECRET_KEY = 'MY_SECRET_KEY'; // non protected endpoint // url - http://localhost:3001/api app.get('/api', (req, res) => { res.status(200).json({ message: 'welcome to api service' }); }); // creating access token // url - http://localhost:3001/api/login app.post('/api/login', (req, res) => { // todo - add request body validation // throw 400 bad request if username or password is null // throw 401 unauthorized if username or password is incorrect // creating payload let nowInSeconds = new Date().getTime() / 1000; let payload = { aud: 'e78dc489-e37e-4aa3-9247-cd6b214da3e6', iss: 'node', sub: 'jcg', iat: nowInSeconds }; // creating access-token const accessToken = jwt.sign(payload, SECRET_KEY, { algorithm: 'HS256', expiresIn: '1h' }); res.status(201).json({ token: accessToken }); }); // protected endpoint // will verify the access token first // url - http://localhost:3001/api/protected // note - add the authorization header in the request otherwise you will get 403 error app.get('/api/protected', ensureToken, (req, res) => { // verifying the jwt token jwt.verify(req.token, SECRET_KEY, { algorithm: 'HS256' }, (err, data) => { if (err) { // console.log(err); res.status(403).json({ message: 'Forbidden' }); } else { // console.log(data); res.status(200).json({ message: 'welcome to protected api service' }); } }); }); // util method function ensureToken(req, res, next) { const bearerHeader = req.headers['authorization']; // console.log('Bearer header received = ' + bearerHeader) if (typeof bearerHeader !== 'undefined') { const bearer = bearerHeader.split(' '); const bearerToken = bearer[1]; req.token = bearerToken; next(); } else { res.status(403).json({ message: 'Forbidden' }); } } // start app const PORT = process.env.port || 3001; app.listen(PORT, () => { console.log(`Application listening on ${PORT}`); });
3. Run the Application
To run the application navigate to the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on port number 3001
.
4. Demo
You are free to use postman or any other tool of your choice to make the HTTP request to the application endpoints.
// Non protected endpoint // HTTP GET http://localhost:3001/api // Creating access token endpoint // HTTP POST http://localhost:3001/api/login // Protected endpoint // HTTP GET http://localhost:3001/api/protected
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we learned how to create a Node.js JWT (JSON Web Token) using the jsonwebtoken
module and verifying the access token while calling the protected endpoint. You can download the source code and the postman collection from the Downloads section.
6. Download the Project
This was a tutorial on how to implement a JWT (JSON web token) in a node.js application.
You can download the full source code of this example here: Node.js JWT Implementation