Blog | G5 Cyber Security

JWT Session Tokens: Security Best Practices

TL;DR

Bearer JWT session tokens need careful handling to prevent security issues. This guide covers how to store, transmit, and validate them securely.

1. Understanding the Risks

JWT (JSON Web Token) session tokens are commonly used for authentication. However, they can be vulnerable if not managed correctly:

2. Secure Storage

Avoid storing JWTs in local storage whenever possible. Here are better options:

  1. HTTP-only Cookies (Recommended): Use HTTP-only cookies with the Secure and SameSite=Strict attributes. This prevents JavaScript access and mitigates XSS risks.
from flask import Flask, make_response

app = Flask(__name__)

@app.route('/login')
def login():
  token = 'your_jwt_token'
  resp = make_response('Login successful!')
  resp.set_cookie('session_token', token, httponly=True, secure=True, samesite='Strict')
  return resp
  • In-Memory Storage (for Single Page Applications): If using a SPA, store the JWT in memory and retrieve it only when needed.
  • Web Workers: Store tokens within Web Workers to isolate them from the main thread’s XSS vulnerabilities.
  • 3. Secure Transmission

    Always transmit JWTs over HTTPS (TLS/SSL). This encrypts the communication channel, preventing interception.

    4. Robust Validation

    Implement thorough JWT validation on the server-side.

    1. Verify Signature: Always verify the token’s signature using your secret key or public key (depending on the signing algorithm).
    const jwt = require('jsonwebtoken');
    
    token = 'your_jwt_token'
    
    jwt.verify(token, 'your_secret_key', (err, decoded) => {
      if (err) {
        // Token is invalid
        console.error(err);
        return res.status(401).send('Invalid token');
      } else {
        // Token is valid
        console.log(decoded);
        return res.status(200).send('Token verified successfully');
      }
    });
  • Check Expiration (exp claim): Ensure the token hasn’t expired.
  • Validate Issuer (iss claim) and Audience (aud claim): Confirm that the token was issued for your application.
  • Consider Refresh Tokens: Use short-lived access tokens combined with long-lived refresh tokens to minimize the impact of compromised tokens.
  • 5. Additional Security Measures

    Exit mobile version