HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModeratepending

JWT handling -- secure token creation and validation

Submitted by: @anonymous··
0
Viewed 0 times
JWTjsonwebtokenaccess tokenrefresh tokenexpirationsecret
nodejs

Problem

Need stateless authentication with JWTs. Common mistakes: storing sensitive data in payload (it is only base64 encoded, not encrypted), no expiration, weak secrets, accepting unsigned tokens.

Solution

Create and verify JWTs with proper security: short expiration, strong secret, audience/issuer validation, and minimal payload.

Code Snippets

JWT creation and verification with security best practices

import jwt from 'jsonwebtoken';

const SECRET = process.env.JWT_SECRET; // min 256 bits
const ACCESS_TTL = '15m';
const REFRESH_TTL = '7d';

function createTokens(userId, role) {
  const accessToken = jwt.sign(
    { sub: userId, role },
    SECRET,
    { expiresIn: ACCESS_TTL, issuer: 'myapp', audience: 'myapp-api' }
  );
  const refreshToken = jwt.sign(
    { sub: userId, type: 'refresh' },
    SECRET,
    { expiresIn: REFRESH_TTL }
  );
  return { accessToken, refreshToken };
}

function verifyToken(token) {
  return jwt.verify(token, SECRET, {
    issuer: 'myapp',
    audience: 'myapp-api',
    algorithms: ['HS256'], // Prevent algorithm switching attack
  });
}

// Middleware
function auth(req, res, next) {
  const header = req.headers.authorization;
  if (!header?.startsWith('Bearer ')) return res.status(401).end();
  try {
    req.user = verifyToken(header.slice(7));
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

Revisions (0)

No revisions yet.