Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Implementing JWT in Node.js

Introduction

JSON Web Tokens (JWT) are a compact and self-contained way for securely transmitting information between parties as a JSON object. This lesson will guide you through implementing JWT for authentication in a Node.js application.

What is JWT?

JWT is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. It is widely used for authentication and information exchange.

Structure of JWT

JWT consists of three parts:

  • Header: Contains metadata about the token, such as the type of token and the signing algorithm.
  • Payload: Contains the claims or the actual data you want to transmit. This can include user information or any other relevant data.
  • Signature: Used to verify that the sender of the JWT is who it claims to be and to ensure that the message wasn't changed along the way.

How to Implement JWT

Step 1: Setting Up the Project

mkdir jwt-example
cd jwt-example
npm init -y
npm install express jsonwebtoken dotenv

Step 2: Creating the JWT

In your main application file (e.g., app.js), you can set up your Express server and create a JWT as follows:

const express = require('express');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();

const app = express();
app.use(express.json());

app.post('/login', (req, res) => {
    const { username, password } = req.body;

    // Validate user credentials (this is just a demonstration)
    if (username === 'user' && password === 'password') {
        const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
        return res.json({ token });
    }
    return res.status(401).send('Invalid credentials');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Step 3: Verifying the JWT

To protect routes in your application, you can create a middleware function to verify the token:

function authenticateToken(req, res, next) {
    const token = req.headers['authorization'] && req.headers['authorization'].split(' ')[1];
    if (!token) return res.sendStatus(401);

    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
    });
}

app.get('/protected', authenticateToken, (req, res) => {
    res.send('This is a protected route');
});

Best Practices

  • Always use HTTPS to protect the token during transmission.
  • Set a short expiration time for tokens and refresh them as needed.
  • Store secrets and keys securely, and do not expose them in your code.
  • Do not include sensitive information in the JWT payload.

FAQ

What is the difference between JWT and sessions?

JWTs are stateless and can be stored in the client, whereas sessions are stateful and usually stored on the server side.

Can I use JWT for authorization?

Yes, JWTs can be used for both authentication and authorization to control access to resources.

How do I handle token expiration?

You can set a short expiration time for tokens and implement a refresh token mechanism to issue new tokens without requiring user credentials.