A quick guide to JWTs

A quick guide to JWTs

ยท

2 min read

[33]

Introduction

JWT Stands for JSON Web Tokens. It is a way to manage authentication and authorization in web applications. JWTs are concise, self-contained tokens that consists of three components: header, payload and signature. Generally, these tokens are employed for the purposes of authentication or information exchange between parties. After a user is successfully logged in, a new JWT is issued; it then gets sent back to the client who will include it in subsequent requests thus authenticating them.

Best Practices for Securing JWTs

Using HTTPS

HTTPS guarantees that the JWTs which are transmitted are encrypted on the mov and hence prevents any man-in-the-middle attack. When HTTP is employed, JWTs become an easy target to intercept and therefore your system becomes insecure.

Implement Proper Token Expiry

JWTs should have a reasonable expiration time which makes it harder for the hackers who may try to steal them.

Rate Limiting and Throttling

To protect your authentication endpoints from brute force attacks and Denial-of-Service (DoS) attacks, rate limiting and throttling mechanisms must be implemented. This will prevent malicious actors from bombarding the server with too many authentication requests.

Example

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

/* use a secure secret key at least 32 characters long eg '9wJMN71@Dx5#p%bTqY!6Rs*eK$A&zP2H' */

const secretKey = process.env.JWT_SECRET;


const createToken = (payload) => {
  try {
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h', algorithm: 'HS256' });
    return token;
  } catch (error) {
    console.error('Error creating JWT:', error.message);
    return null;
  }
};


const verifyToken = (token) => {
  try {
    const decoded = jwt.verify(token, secretKey);
    return decoded;
  } catch (error) {
    console.error('Error verifying JWT:', error.message);
    return null;
  }
};


const payload = { user_id: 123456 };
const token = createToken(payload);
if (token) {
  console.log('JWT created successfully:', token);

  const decoded = verifyToken(token);
  if (decoded) {
    console.log('JWT verified successfully. Decoded payload:', decoded);
  } else {
    console.log('JWT verification failed.');
  }
}
ย