Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0007

JWT access tokens with rotating refresh tokens

Trạng thái
accepted
Ngày
2026-09-21
Người quyết định
Alex

Context

The API serves three roles (admin, instructor, student) and, later, a mobile client. It needs stateless request authentication, sessions that last weeks, and a way to end a session that has leaked. ADR-0002 (point 8) fixed the principle. This record fixes the mechanics as built in apps/api/src/modules/auth.

Decision

  • Access token: a JWT signed with JWT_ACCESS_SECRET (at least 32 characters, checked at boot), valid for JWT_ACCESS_TTL_SECONDS (default 900). Claims are sub, email, role, plus iss set to JWT_ISSUER (smartlearn-ai). The strategy verifies the issuer, parses the claims with the shared jwtPayloadSchema, and re-reads the user, so a deactivated account stops working at once.
  • Refresh token: 48 random bytes, opaque, valid for JWT_REFRESH_TTL_DAYS (default 30). Only its SHA-256 hash is stored, in RefreshToken.
  • Rotation is atomic. /auth/refresh revokes with one updateMany that matches tokenHash, revokedAt: null and expiresAt > now, and continues only if exactly one row changed. Two concurrent refreshes with the same token cannot both succeed.
  • Reuse detection. If the presented token exists but is already revoked, every live refresh token of that user is revoked and the event is logged at error.
  • Login is throttled to 5 attempts per minute per client IP (LOGIN_THROTTLE); the global limit is 120 per minute. A missing user and a wrong password take the same time: bcrypt runs against a dummy hash when the user does not exist.
  • Private by default: the global JwtAuthGuard protects every route; @Public() opts out.

Alternatives considered

  • Server sessions in Redis. Revocation is one delete, but every request needs a Redis read, and a mobile client prefers bearer tokens.
  • Long-lived access tokens only. No way to end a leaked session before it expires.
  • Passport local strategy. Adds a layer for what is one compare call.

Consequences

  • Tokens travel in the response body today. Where the web client keeps them (httpOnly cookie through the single origin, or memory) is decided with the web auth work.
  • Every authenticated request costs one user lookup. That is accepted for immediate deactivation.
  • Throttle counters are in memory, which is correct only for a single api instance.