Modern Authentication with JWT

By Amitesh Maurya | Category: Backend & Security | 10 min read

JSON Web Tokens (JWT) have become the standard for stateless authentication in modern web applications. In this post, you'll learn how JWT works, how to implement secure authentication flows, and best practices to keep your users and APIs safe.

1. What is JWT?

JWT (JSON Web Token) is a compact, URL-safe token format used to securely transmit information between parties. A JWT consists of three parts: header, payload, and signature. It is commonly used for authentication and authorization in web and mobile apps.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTYifQ.s5v8k9w1v2y3z4x5w6y7z8a9b0c1d2e3

2. How JWT Authentication Works

  1. User Login: The user submits credentials (e.g., email & password).
  2. Token Issuance: The server verifies credentials and issues a signed JWT.
  3. Client Storage: The client stores the JWT (usually in HTTP-only cookies or localStorage).
  4. Authenticated Requests: The client sends the JWT in the Authorization header for protected API calls.
  5. Server Validation: The server validates the JWT signature and extracts user info from the payload.

3. Implementing JWT in Node.js

Here's a simple example using jsonwebtoken in Node.js:

const jwt = require('jsonwebtoken');

// Sign a token
const token = jwt.sign({ userId: '123456' }, 'your-secret-key', { expiresIn: '1h' });

// Verify a token
try {
  const decoded = jwt.verify(token, 'your-secret-key');
  console.log(decoded);
} catch (err) {
  // Invalid token
}

4. Security Best Practices

  • Use HTTPS: Always transmit JWTs over HTTPS to prevent interception.
  • Store Securely: Prefer HTTP-only cookies over localStorage to mitigate XSS attacks.
  • Short Expiry: Set short token lifetimes and use refresh tokens for long sessions.
  • Validate Signature: Always verify the JWT signature on the server.
  • Blacklist/Rotate: Support token revocation and rotation for compromised accounts.
  • Minimal Payload: Never store sensitive data (like passwords) in the JWT payload.

5. Common Pitfalls to Avoid

  • Never trust data from the JWT payload without validation.
  • Don’t use weak or public secrets for signing tokens.
  • Don’t store JWTs in browser storage if you can avoid it.
  • Don’t forget to handle token expiration and renewal.

Conclusion

JWTs are a powerful tool for modern authentication, but they must be used with care. By following best practices and understanding the security implications, you can build robust, scalable, and secure authentication systems for your applications.