Store a JWT secret in one of two tiers: an environment variable injected at deploy time (with a local .env file that never reaches Git), or a secrets manager such as HashiCorp Vault, GCP Secret Manager, or AWS Secrets Manager and SSM Parameter Store backed by AWS KMS. Rotate the signing secret every 90 to 180 days for internal tools and every 30 to 90 days for tokens that leave your network, and immediately after any suspected leak. A rotation that keeps users signed in needs two keys alive at once: add the new key next to the old one, put its id in the token header as kid, let services sign with the new key while they still verify the old one, and delete the old key once every token it signed has expired. This page covers the three concrete storage setups, the four places a secret must never go, a rotation schedule you can defend, and the four-step dual-key procedure with code.

Which storage tier does your JWT secret need?

A JWT secret is effectively a password for your whole token system: anyone who has it can mint tokens for any user, so treat it like a root credential. Start with the simplest tier that covers your risk, and move up when the number of services, environments or people with access grows.

Where a JWT secret can live and what each option costs
SetupWorks well forTrade-off
Environment variable injected at deploy timeOne service, one or two environments, a small teamFastest to start; anyone with deploy access or a shell on the host can read it, and rotation means updating every host.
.env file loaded only in local developmentDeveloper laptops and test runsConvenient and disposable; must be git-ignored and never copied to production.
HashiCorp Vault or GCP Secret ManagerSeveral services or teams, audit requirements, versioned rotationAccess policies, version history and audit logs; you run or pay for another service and must give each service an identity.
AWS Secrets Manager or SSM Parameter Store with AWS KMSAWS workloads that already use IAM rolesValues encrypted by KMS and readable only by permitted roles; per-region setup, KMS request costs and IAM policy work.

The tiers combine rather than compete: the manager holds the value and the application still reads JWT_SECRET through an injected environment variable or a small loader. Keeping the variable name stable turns a move from .env to Vault to KMS into a deployment change, not a code change.

Option 1: an environment variable and a local .env file

Generate the value once with the standard library, or with OpenSSL on a host that has no Python:

# 32 random bytes as 64 hex characters
python3 -c "import secrets; print(secrets.token_hex(32))"

# the same thing on a host that only has OpenSSL
openssl rand -hex 32

Keep the local value in a .env file, and commit an example that lists the names without secrets:

# .env - local development only
JWT_SECRET=replace-with-the-64-character-value
JWT_ISSUER=example-api
# .gitignore
.env
.env.*
!.env.example

Restrict the file, load it for local runs, and let the platform inject the same variable in production:

chmod 600 .env
import os
from pathlib import Path

from dotenv import load_dotenv

load_dotenv(Path(__file__).with_name(".env"))


def require_jwt_secret() -> bytes:
    value = os.environ.get("JWT_SECRET", "").strip()
    if not value:
        raise SystemExit("JWT_SECRET is not set")
    secret = value.encode("utf-8")
    if len(secret) < 32:
        raise SystemExit("JWT_SECRET must be at least 32 bytes")
    return secret

In production the file does not exist. A systemd unit points at an environment file owned by the service user:

[Service]
User=jwt-api
EnvironmentFile=/etc/jwt-api/jwt.env
ExecStart=/opt/jwt-api/venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000

Docker Compose does the same with an env_file for non-sensitive settings and a secrets entry for the key, which appears inside the container under /run/secrets/. Kubernetes should reference a Secret with secretKeyRef so the value never sits in a manifest. In every case the value lives in the platform's secret store and in the process memory, never in the image or the repository.

Option 2: HashiCorp Vault

Vault adds per-service policies, versioned writes and an audit log, which is what you need once more than one team can deploy. Enable KV v2 so old versions stay readable during a rotation, then write the first version:

vault secrets enable -path=secret kv-v2

vault kv put secret/jwt-api/production \
  secret="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"

Give each service its own read-only policy instead of sharing a root token:

path "secret/data/jwt-api/production" {
  capabilities = ["read"]
}

path "secret/metadata/jwt-api/production" {
  capabilities = ["read"]
}
vault policy write jwt-api-read jwt-api-read.hcl

Inside Kubernetes, use the Vault Kubernetes auth method so a pod authenticates with its service account; outside a cluster, use AppRole or your cloud provider's IAM auth method. The application reads the value at start-up and keeps it in memory:

import os

import hvac


def load_jwt_secret() -> str:
    client = hvac.Client(url=os.environ["VAULT_ADDR"])
    client.auth.approle.login(
        role_id=os.environ["VAULT_ROLE_ID"],
        secret_id=os.environ["VAULT_SECRET_ID"],
    )
    if not client.is_authenticated():
        raise RuntimeError("Vault authentication failed")
    version = client.secrets.kv.v2.read_secret_version(
        path="jwt-api/production",
        mount_point="secret",
    )
    return version["data"]["data"]["secret"]

Hard-coding VAULT_ROLE_ID and VAULT_SECRET_ID in the image is the same mistake as hard-coding the secret. Kubernetes auth avoids the secret_id entirely, and Vault Agent can render the value into a file and refresh it when the version changes. Cache the result for the life of the process instead of calling Vault on every request.

During rotation, vault kv put writes a new version and keeps the previous one, so rolling back is a version read rather than a restore. Delete old versions only after the overlap window has passed, and keep the secret path out of request logs.

Option 3: AWS KMS with Secrets Manager or SSM

AWS KMS is a key service, not a secret store: it encrypts and decrypts payloads of up to 4 KB with key material you never see, and CloudTrail records every use. Two patterns cover most setups. The first stores the secret in AWS Secrets Manager or in an SSM Parameter Store SecureString; both encrypt with a KMS key, and the application fetches the value through the AWS SDK. The second encrypts the secret once with kms:Encrypt, keeps only the ciphertext in the deployment configuration, and calls kms:Decrypt at start-up.

For the envelope pattern, encrypt the value once and delete the plaintext file:

python3 -c "import secrets; print(secrets.token_hex(32))" > jwt-secret.txt

aws kms encrypt \
  --key-id alias/jwt-api \
  --plaintext fileb://jwt-secret.txt \
  --encryption-context app=jwt-api,env=production \
  --query CiphertextBlob --output text > jwt-secret.enc.b64

rm jwt-secret.txt

Store the base64 ciphertext in the deployment configuration as JWT_SECRET_CIPHERTEXT and decrypt it in the process at boot:

import base64
import os

import boto3


def load_jwt_secret() -> str:
    kms = boto3.client("kms", region_name=os.environ["AWS_REGION"])
    ciphertext = base64.b64decode(os.environ["JWT_SECRET_CIPHERTEXT"])
    response = kms.decrypt(
        CiphertextBlob=ciphertext,
        EncryptionContext={"app": "jwt-api", "env": "production"},
    )
    return response["Plaintext"].decode("utf-8").strip()

What matters is the IAM boundary: the application role gets kms:Decrypt on that one key and nothing else, while a deploy role owns kms:Encrypt, key creation and policy changes. Use a different KMS key per environment, turn on automatic rotation (KMS rotates key material on a schedule, 365 days by default, and keeps old material so existing ciphertext still decrypts), and cache the plaintext in memory so you do not pay for a KMS call on every request. The Secrets Manager variant is shorter to operate: store the value there and call get_secret_value, which adds versioning and scheduled rotation for you.

Four places a JWT secret must never be stored

Most leaks are boring: a value ends up somewhere convenient and stays there for years. These are the four places that cause the most incidents.

  1. In source control. That includes public and private repositories, committed config files, Helm values and CI scripts. Deleting the line in a later commit does not delete the history, and forks, caches and build logs keep copies. If a secret ever reached a commit, rotate it instead of rewriting history and hoping nobody looked.
  2. In front-end code. Browser bundles, mobile apps and public JavaScript can all be read by the visitor, so anything inside them is public. A signing secret in a client lets anyone mint tokens, which means token creation belongs on a server you control.
  3. In logs, error trackers, APM traces or crash dumps. One debug print of the environment, or one captured request body, copies the secret into a system with weaker access control. Scrub secrets from exceptions, disable body logging on auth routes, and pass sensitive values through a redaction filter before they reach a log aggregator.
  4. In client-side storage or inside the token. Do not put the signing secret in a cookie, localStorage, sessionStorage or a URL query string, and do not put it in a JWT: the payload is only Base64URL-encoded and anyone can read it. Cookies and storage hold tokens, never the key that signs them.

A quick test for any new pipeline: if the value could show up in a screenshot of a dashboard, a build log or a support ticket, it belongs in a secret store rather than a configuration value.

How often should you rotate a JWT secret?

There is no universal interval. Rotation is a risk decision: the more services and people can read the secret, the wider it travels, and the longer each token lives, the more a stolen key is worth. These intervals are defensible starting points rather than rules:

Suggested JWT secret rotation intervals by exposure
SituationSuggested intervalWhy
Internal tools behind a VPN or zero-trust proxy90-180 daysA small audience and short sessions; a long interval keeps operational work low.
Public API tokens or customer-facing sessions30-90 daysTokens leave your network, so a shorter window limits how long a leaked key can sign valid tokens.
Long-lived tokens, or payments, health and other high-risk data30 days or on every deploymentThe blast radius is large; keep token lifetimes short as well.
Suspected exposure, departure of someone with access, or a failed auditImmediatelyTreat the key as already public and run the emergency procedure below.

Two constraints shape the schedule. The interval has to be longer than the overlap you need, or the next rotation starts before the previous one finishes, and it should be paired with short-lived tokens: a 15-minute access token limits damage far more than any rotation calendar. A rotation procedure that has never run in staging is not a procedure, so run it once against a real deployment before you depend on it.

How do you rotate a JWT secret without logging users out?

The safe pattern is verify before sign: add the new key while the old one is still trusted, then move signing over, then retire the old key after the last token it signed has expired. A kid (key id) header tells verifiers which key signed a token, so both keys can be live during the overlap.

  1. Create and store the new secret next to the old one. Name both keys explicitly, for example JWT_SECRET_2026_03 and JWT_SECRET_2026_11, or keep two versions in Vault or two encrypted values in KMS. Nothing changes for users yet.
  2. Deploy verifiers that accept both keys. The verification code reads kid from the token header, looks up the matching key and checks the signature; signing still uses the old key. Every service that verifies tokens needs this deploy before the next step.
  3. Switch signing to the new key. Point JWT_ACTIVE_KID at the new id and deploy. New tokens carry the new kid, while tokens issued minutes ago still verify because their kid still resolves to the old key.
  4. Retire the old key after the overlap window. Wait at least the longest access-token lifetime plus allowed clock skew; for 15-minute tokens a 30 to 60 minute window is enough, while refresh tokens need a plan of their own. Watch signature failures in the logs, then delete the old key and its configuration entry.

Dual-key signing and verification code

import os
from typing import Any

import jwt

# kid -> secret. During a rotation both entries exist:
# the active key signs, the previous key only verifies.
KEY_RING: dict[str, str] = {
    "2026-03": os.environ["JWT_SECRET_2026_03"],
    "2026-11": os.environ["JWT_SECRET_2026_11"],
}
ACTIVE_KID = os.environ.get("JWT_ACTIVE_KID", "2026-11")


def sign_access_token(claims: dict[str, Any]) -> str:
    return jwt.encode(
        claims,
        KEY_RING[ACTIVE_KID],
        algorithm="HS256",
        headers={"kid": ACTIVE_KID},
    )


def verify_access_token(token: str) -> dict[str, Any]:
    kid = jwt.get_unverified_header(token).get("kid")
    if kid not in KEY_RING:
        raise jwt.InvalidTokenError(f"unknown kid: {kid!r}")
    return jwt.decode(
        token,
        KEY_RING[kid],
        algorithms=["HS256"],
        options={"require": ["exp", "iat", "sub"]},
    )
# .env - two keys during the rotation window
JWT_SECRET_2026_03=replace-with-the-previous-value
JWT_SECRET_2026_11=replace-with-the-new-value
JWT_ACTIVE_KID=2026-11

The kid travels in plain text, so keep it a label such as a date or a version, never the key or a hash of it. Look the key up by kid and verify the signature before trusting any other claim; an unknown kid is a failed token, not a reason to try every key. On Python 3.9 and newer the dict[...] annotations above work as written; on 3.8 add from __future__ import annotations to the top of the module.

How kid and a JWKS endpoint fit together

kid is a standard JOSE header, and a JWKS document is a JSON list of public keys that a verifier downloads, usually from /.well-known/jwks.json, and caches. The verifier reads kid from the token, finds the matching key in the JWKS and checks the signature. During a rotation the document simply contains both public keys for the length of the overlap, so nothing has to be coordinated with third-party clients.

HS256 breaks this pattern because it is symmetric: there is no public half to publish, and a JWKS entry with an HMAC secret would hand the signing key to anyone who can mint tokens. If other teams or customers must verify your tokens, sign with RS256, ES256 or EdDSA and publish only the public keys. Rotation then swaps the key pair and both public keys stay in the JWKS during the overlap:

import json

from jwt.algorithms import RSAAlgorithm


def jwks_entry(public_key_pem: bytes, kid: str) -> dict:
    jwk = json.loads(RSAAlgorithm.to_jwk(public_key_pem))
    jwk.update({"kid": kid, "use": "sig", "alg": "RS256"})
    return jwk


# Publish {"keys": [jwks_entry(pub_2026_03, "2026-03"),
#                   jwks_entry(pub_2026_11, "2026-11")]}
# Sign RS256 tokens with the private key and headers={"kid": "2026-11"}.

Keep the kid labels the same when you move from HS256 to RS256 and the switch becomes an ordinary rotation instead of a redesign. PyJWT needs the cryptography package for RSA keys: pip install "PyJWT[crypto]". The standards behind these headers are published as RFC 7515, JSON Web Signature and RFC 7517, JSON Web Key.

What do you do when a JWT secret leaks?

Treat it as an active compromise, not a cleanup task: anyone with the value can mint tokens for any user until you stop trusting the leaked key.

  1. Issue a new signing key and deploy it as the only accepted key. Skip the dual-key window this time; forcing everyone to sign in again is the point.
  2. Revoke what you can revoke. Delete server-side sessions, bump a token-version claim stored per user, rotate refresh tokens, and clear caches that may hold long-lived access tokens.
  3. Rotate every copy of the value. CI variables, deployment configs, backups, Vault versions, KMS ciphertext and any other service that reused the same string all count as leaked.
  4. Watch for abuse. Shorten access-token lifetimes for a while and review application logs and CloudTrail for token minting or unusual API calls during the exposure window.
  5. Close the loop. Follow your breach process if personal data could have been reached, record who had access and when, and move the value to a manager with audit logs plus a rotation step in the release checklist.

Frequently asked questions

Will rotating the JWT secret log users out?

Not if you keep both keys alive for an overlap window. Tokens signed with the old key keep verifying until their exp claim passes, so visitors who were already signed in stay signed in. If you remove the old key immediately, every token fails verification at once and everyone is signed out. Refresh tokens and server-side sessions follow their own rules: rotating the signing key does not touch passwords or session cookies, but if refresh tokens are JWTs signed with the same key, give them the same overlap or revoke them deliberately.

Is the kid header required?

No. A service that uses a single key can verify tokens without any kid header. kid becomes necessary the moment two keys are valid at the same time, because the verifier has to know which key to try, and adding it before your first rotation makes that rotation uneventful. Keep kid a non-secret label such as a date or a version, read it from the header to look up the key, and then verify the signature with that key. Never trust other claims before the signature check, and reject a token whose kid you do not recognize.

How do I automate rotation without a person in the loop?

Let the secret store produce the new version and let your deployment pipeline consume it. AWS Secrets Manager has managed rotation functions, Vault KV v2 keeps versions you can write from a scheduled job, and a KMS-encrypted value can be re-encrypted on a schedule. The pipeline then deploys code that accepts both keys, flips JWT_ACTIVE_KID to the new key, waits for the token lifetime to pass, and disables the old version in a final scheduled step. Add an alert on signature verification failures, run the whole procedure once in staging, and make every step idempotent so a retried job cannot delete a key that is still in use.

What should I do if the JWT secret leaks?

Treat it as an active compromise and rotate immediately without an overlap window: deploy a new key as the only accepted key, then revoke server-side sessions and refresh tokens and rotate every copy of the value in CI, deployment configs, backups, Vault and KMS. Shorten access-token lifetimes for a while, review logs and CloudTrail for token minting during the exposure window, and follow your breach process if personal data could have been reached. Cleaning up the place the secret appeared is not enough; assume the old value is public forever.

How can several services share one JWT secret safely?

Give every service read access through one secret manager and its own identity, not a copy of a .env file passed around in chat or a wiki. During a rotation, deploy verifiers that accept both keys to every service before the signer switches, because a service still running only the old key will reject new tokens. For services outside your control, do not distribute an HMAC secret at all: sign with RS256 or ES256, publish the public keys in a JWKS, and let each verifier fetch them. The signing key then stays in one place while verification spreads.

Should access tokens and refresh tokens use the same secret?

Use separate keys, or at least separate issuer and audience values. Access tokens are short-lived and travel to resource servers; refresh tokens live much longer and are stored and revoked server-side. A different signing key keeps a leaked access-token key from minting refresh tokens, and a different audience keeps a token issued for one service from being accepted by another. Use separate keys per environment as well, so a staging token can never verify in production.

Generate a JWT secret key

Next: generate the key itself with the JWT signing key generator, then inspect and verify a JWT token with it.