DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Session Management Security

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Session Management Security

Introduction

Session management is the mechanism by which a web application maintains state across multiple requests from the same user. Flawed session management leads to session hijacking, fixation, and replay attacks. A robust session management strategy must address token generation, storage, transmission, rotation, and invalidation.

JWT vs Opaque Tokens

JSON Web Tokens

JWTs are self-contained tokens carrying claims in a signed JSON payload. They enable stateless authentication — the server validates the signature without database lookups.

import jwt

from datetime import datetime, timedelta

Generate a JWT access token

def create_access_token(user_id, roles, secret_key):

payload = {

'sub': user_id,

'roles': roles,

'iat': datetime.utcnow(),

'exp': datetime.utcnow() + timedelta(minutes=15),

'jti': secrets.token_hex(16), # Unique token ID for revocation

'type': 'access'

}

return jwt.encode(payload, secret_key, algorithm='HS256')

Generate a refresh token

def create_refresh_token(user_id, secret_key):

payload = {

'sub': user_id,

'exp': datetime.utcnow() + timedelta(days=7),

'jti': secrets.token_hex(16),

'type': 'refresh'

}

return jwt.encode(payload, secret_key, algorithm='HS256')

Verify and decode

def verify_token(token, secret_key):

try:

payload = jwt.decode(token, secret_key, algorithms=['HS256'])

Check if token is revoked (check jti against blocklist)

if is_revoked(payload['jti']):

raise jwt.InvalidTokenError('Token revoked')

return payload

except jwt.ExpiredSignatureError:

raise

except jwt.InvalidTokenError:

raise

JWT advantages: stateless, self-validating, carries user claims. Disadvantages: cannot revoke without a blocklist, payload is signed not encrypted (unless JWE), token size can be large.


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)