JWT Authentication with Node.js
JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining sessions on the client side instead of storing sessions on the server. Here, we will implement the JWT authentication system in NodeJs.
Prerequisites:
Steps to Installation of the Express Module:
Step 1: Run the following commands to initialize the project and create an index file & env file. (Make sure you have node and npm installed)
npm init -y
Step 2: Installing required packages
npm install express dotenv jsonwebtoken
Step 3: Create our ServerImporting all the dependencies and creating a server using express.js
Step 4: Create Configuration File (.env) This files contains those variables that we need to pass to our application’s environment.
PORT = 5000
JWT_SECRET_KEY = gfg_jwt_secret_key
TOKEN_HEADER_KEY = gfg_token_header_key
Step 5: Create Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.
Step 6: Create Route for Validating JWT Creating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.
Project Structure:
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
}
Example: Below is the code example of the JWT Authentication with Node JS
Javascript
const express = require( 'express' );
const dotenv = require( 'dotenv' );
const jwt = require( 'jsonwebtoken' );
const app = express();
dotenv.config();
let PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is up and running on ${PORT} ...`);
});
app.post( "/user/generateToken" , (req, res) => {
let jwtSecretKey = process.env.JWT_SECRET_KEY;
let data = {
time: Date(),
userId: 12,
}
const token = jwt.sign(data, jwtSecretKey);
res.send(token);
});
app.get( "/user/validateToken" , (req, res) => {
let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;
let jwtSecretKey = process.env.JWT_SECRET_KEY;
try {
const token = req.header(tokenHeaderKey);
const verified = jwt.verify(token, jwtSecretKey);
if (verified) {
return res.send( "Successfully Verified" );
} else {
return res.status(401).send(error);
}
} catch (error) {
return res.status(401).send(error);
}
});
|
Steps to Run the Server:
node index.js
Output: Send Requests and Get Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94
Successfully Verified
Last Updated :
05 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...