Security & Authentication

What is JWT (JSON Web Token)?

Learn about JWT - an open standard for securely transmitting information between parties as a JSON object.

5 min read
#jwt#authentication#security#token#authorization#web-security

What is JWT?

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed using a secret (with HMAC) or a public/private key pair (with RSA or ECDSA).

JWT Structure

A JWT consists of three parts separated by dots (.): Header, Payload, and Signature.

1. Header

Contains metadata about the token type and the signing algorithm being used.

json
{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

Contains the claims - statements about an entity (typically the user) and additional metadata. There are three types of claims: registered, public, and private claims.

json
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "exp": 1516242622
}

3. Signature

Created by encoding the header and payload with a secret key. This ensures the token hasn't been tampered with.

javascript
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret
)

How JWT Works

The authentication flow using JWT typically follows these steps:

  • User logs in with username and password
  • Server validates credentials and creates a JWT token
  • Server returns the JWT to the client
  • Client stores JWT (usually in localStorage or httpOnly cookies)
  • For subsequent requests, client sends JWT in Authorization header
  • Server verifies JWT signature and allows or denies the request

Advantages of JWT

  • Stateless: Server doesn't need to store sessions, making it easy to scale horizontally
  • Compact: Small size makes it easy to send through URL, POST parameters, or HTTP headers
  • Self-contained: Payload contains all required user information, reducing database queries
  • Cross-domain: Works well with CORS and mobile applications
  • Performance: No need to query database to verify tokens on every request
  • Decoupled: Can be generated and verified by different services in a microservices architecture

Disadvantages and Security Considerations

  • Cannot revoke: Tokens remain valid until expiration - implement token blacklist if needed
  • Size: Larger than traditional session IDs, increasing bandwidth usage
  • Secret management: Requires secure storage and rotation of secret keys
  • XSS vulnerability: If stored in localStorage, tokens can be stolen via XSS attacks
  • Token expiration: Need to balance security (short expiration) with user experience
  • No encryption: JWT is signed, not encrypted - don't store sensitive data in payload

Common Use Cases

  • Authentication: Single Sign-On (SSO) - authenticate once for multiple services
  • Authorization: Control access to resources based on user permissions in token
  • Information Exchange: Securely transmit information between parties
  • Mobile Apps: Authenticate mobile applications without cookies
  • Microservices: Share authentication state across distributed services
  • API Authentication: Secure REST APIs and GraphQL endpoints

Best Practices

  • Always use HTTPS to transmit JWT tokens
  • Set reasonable expiration times (typically 15-60 minutes)
  • Use refresh tokens for long-lived sessions
  • Never store sensitive data in the payload
  • Always validate token signatures on the server
  • Use strong secret keys and implement key rotation
  • Consider using httpOnly cookies instead of localStorage
  • Implement token blacklist for critical operations requiring logout
  • Use appropriate algorithms (avoid 'none' algorithm)
  • Validate all claims (exp, iat, nbf, iss, aud) on the server

Conclusion

JWT is a powerful tool for modern authentication and authorization systems. While it offers significant advantages in terms of scalability and performance, it's crucial to understand its limitations and implement it securely. Always consider your specific use case and security requirements when choosing JWT for your application.