jwt npm

JSON Web Token is a way of securely transmitting information between two parties. It is widely used in web applications for authentication and authorization purposes. In this article, we make a project that demonstrates a basic implementation of JWT in a Node.js application. The application features user registration with password hashing, login and generating tokens.

Prerequisites:

Features of JWT

  • JSON Format: The token is represented as a JSON object, making it easy to work with in web environments.
  • Security: JWTs can be signed using cryptographic algorithms, such as HMAC. This signature ensures the integrity of the data and helps prevent unauthorized modifications.
  • Compactness: It stores essential information within the token, making it lightweight and efficient to transmit.
  • Validity: JWTs can include an expiration time which limits their validity period.
  • Customizable: JWTs can include additional user data or permissions through custom claims.

Approach

  • Import the required modules and configure the Express application to use JSON parsing.
  • Implement a register function to hash passwords using bcrypt and store user details.
  • Implement a login function to verify user credentials and generate a JWT upon successful authentication.
  • Start the Express server and test user registration and login functionality with JWT token generation.
  • Initialize Node.js project and install express, jsonwebtoken, and bcryptjs.

Steps to Create Application

Step 1: Create a root directory and navigate to it using the following command.

mkdir jwt-demo-app
cd jwt-demo-app

Step 2 : Initialize your project by this command.

npm init -y

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install express jsonwebtoken bcryptjs

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"bcryptjs": "^2.4.3",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2"
}

Example: Implementation to show the use of JWT with an example.

JavaScript
// app.js 

import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';


const app = express();
const PORT = 3000;
const SECRET_KEY = 'xxxx-xxxx';

app.use(express.json());

// This will act as our 'database'
let users = [];

// Register route
async function register(username, email, password) {
    // Hash the password
    const hashedPassword = await bcrypt.hash(password, 8);
    // Save the user
    users.push({ username, password: hashedPassword, email });
    console.log('User registered Successfully.');
    return true;
}

// Login route
async function login(email, password) {
    // Find the user
    const user = users.find(user => user.email == email);
    if (!user) {
        console.log('User not found.')
        return null;
    }
    // Check the password
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
        console.log('Invalid credentials');
        return null;
    }
    console.log('User Details', user, '\n')
    // Generate a JWT
    const token = jwt.sign(
        { email },
        SECRET_KEY,
        { expiresIn: '1h' });
    console.log('Token', token, '\n')
    return token;
}

// register a user 
register('Sandeep', 'ex@gmail.com', 'exm123')

setTimeout(() => {
    login('ex@gmail.com', 'exm123')
}, 5000); // after 5 second login 

app.listen(PORT, () => {
    console.log(`Server is running  ${PORT}`);
});

Step to Run Application: Run the application using the following command from the root directory of the project

node .\app.js

Output: Your project will be shown in the URL http://localhost:3000/

JWT Output



Contact Us