Ultimate Guide to JSON Web Token (jsonwebtoken) API with Examples

Introduction to JSON Web Token (jsonwebtoken)

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It is widely used for authentication and authorization purposes. The `jsonwebtoken` library in Node.js provides a straightforward way to work with JWTs. In this guide, you’ll learn how to use various APIs provided by the `jsonwebtoken` library with examples.

Installation

  npm install jsonwebtoken

Generating a Token

Generate a JWT using the sign method:

  const jwt = require('jsonwebtoken');
  const payload = { userId: 123, username: 'john_doe' };
  const secret = 'your-256-bit-secret';
  const token = jwt.sign(payload, secret, { expiresIn: '1h' });
  console.log(token);

Verifying a Token

Verify the token using the verify method:

  jwt.verify(token, secret, (err, decoded) => {
    if (err) {
      return console.error('Token verification failed:', err);
    }
    console.log('Decoded payload:', decoded);
  });

Decoding a Token

Decode the token without verifying its signature:

  const decoded = jwt.decode(token);
  console.log('Decoded payload:', decoded);

Using Callbacks and Promises

You can use callbacks or promises with the jsonwebtoken library:

With Callback:

  jwt.sign(payload, secret, { expiresIn: '1h' }, (err, token) => {
    if (err) {
      return console.error('Error signing token:', err);
    }
    console.log('Generated token:', token);
  });

With Promise:

  const signToken = (payload, secret) => {
    return new Promise((resolve, reject) => {
      jwt.sign(payload, secret, { expiresIn: '1h' }, (err, token) => {
        if (err) {
          reject(err);
        } else {
          resolve(token);
        }
      });
    });
  };

  signToken(payload, secret)
    .then(token => console.log('Generated token:', token))
    .catch(err => console.error('Error signing token:', err));

Creating a Token for an Application

Here’s an example of a simple Express application using JSON Web Token:

  const express = require('express');
  const jwt = require('jsonwebtoken');

  const app = express();
  const secret = 'your-256-bit-secret';

  app.use(express.json());

  app.post('/login', (req, res) => {
    const user = { id: 1, username: 'john_doe' };
    const token = jwt.sign(user, secret, { expiresIn: '1h' });
    res.json({ token });
  });

  app.get('/protected', (req, res) => {
    const token = req.headers['authorization'];

    if (!token) {
      return res.status(401).send('Access Denied');
    }

    jwt.verify(token, secret, (err, decoded) => {
      if (err) {
        return res.status(403).send('Invalid Token');
      }

      res.send('Welcome to protected route, ' + decoded.username);
    });
  });

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

Conclusion

JSON Web Token (jsonwebtoken) is a powerful library that works seamlessly for creating, verifying, and decoding JWTs in your Node.js application. This guide covered various method examples and a practical application example to provide a thorough understanding of how to use `jsonwebtoken` effectively.

Hash: 44701fc5b201f819a01da9d5f4f93c393c2f1100ccfef5f5f32cf16549e81c03

Leave a Reply

Your email address will not be published. Required fields are marked *