Hardcoded JWT signing secret

Hardcoded JWT signing secret

Description

Storing a symmetric JWT signing secret directly in source code lets anyone who can read the repository or deployment files recover it. An attacker may forge tokens and bypass authentication or permission checks in systems that trust the key.

Potential impact

  • Acceptance of tokens signed with the exposed key may enable impersonation or unauthorized permissions.
  • An attacker may read or change data within those permissions. Key replacement and invalidation of existing tokens may be necessary.

Remediation

  • Supply secrets through a restricted secret store or deployment environment instead of storing them in code.
  • Use a sufficiently long cryptographically random key. Protect access to environment variables or configuration files, and prevent disclosure through logs.
  • Replace exposed keys and stop trusting tokens created with them. Do not issue tokens when the secret is missing.

Examples

These excerpts use the legacy JWT.sign API in jose 1.28.2. For new code, use SignJWT in a supported version. The examples compare key supply only; configure algorithm, issuer, audience and expiration policies separately.

Before

javascript
const { JWT } = require('jose')
const payload = {foo: 'bar'}

// Secret embedded directly in source code
const token = JWT.sign(payload, 'my-secret-key')

After

javascript
const { JWT } = require('jose')
const payload = {foo: 'bar'}

// Read the secret from an environment variable
const secret = process.env.JWT_SECRET
if (!secret) {
  throw new Error("JWT_SECRET is required")
}
const token = JWT.sign(payload, secret)

Explanation:

  • Before: The secret my-secret-key is visible in the code. A reader can forge tokens and attempt unauthorized access to systems that trust it.
  • After: process.env.JWT_SECRET supplies the secret without embedding it in code, and issuance stops when it is missing. The key still needs sufficient randomness and protected storage. Separate keys can be supplied for different environments.

References