To generate a JWT secret in Python, call secrets.token_hex(32) and store the 64-character result in an environment variable such as JWT_SECRET. token_hex(32) reads 32 bytes from os.urandom and returns 256 bits of cryptographically secure randomness in ASCII form, which fits a .env file, a CI variable or a container secret. Use secrets.token_bytes(32) when the signing library takes raw bytes, and secrets.token_urlsafe(32) when you need a shorter string that survives URLs and HTTP headers. Avoid random.random(), random.randbytes() and hand-typed passphrases: the random module is built for simulations and is predictable once an attacker sees enough output. After the value exists, load it at start-up, pass it to the same library that creates and verifies your tokens, and fail loudly when the variable is missing instead of falling back to a default.

Which secrets function should you use?

The secrets module is the standard library's cryptographically secure random generator. It draws bytes from the operating system entropy source (os.urandom() on Linux, macOS and Windows) instead of a software-generated seed, so there is nothing to seed or tune. For a JWT secret you need one call; the three functions below differ in the format they return, not in the randomness behind it. The Python documentation for the secrets module covers the remaining helpers for passwords, tokens and secure comparisons.

Output of the three secrets functions for a 32-byte JWT secret
FunctionReturnsLengthUse it when
secrets.token_bytes(32)bytes32 bytesYour JWT library takes a bytes key and the value never needs to be pasted into a config file.
secrets.token_hex(32)str, 0-9 and a-f64 charactersThe secret lives in .env, a CI variable or a configuration system that prefers plain ASCII.
secrets.token_urlsafe(32)str, Base64URL alphabet43 charactersYou want the same 256 bits in fewer characters and need a value that is safe in URLs, headers or connection strings.

All three start from the same 32 random bytes, so they carry 256 bits of entropy; the difference is only the encoding, and therefore how many characters you have to store.

import secrets

# 32 bytes = 256 bits, the minimum key size for HS256 in PyJWT.
raw_key = secrets.token_bytes(32)     # bytes
hex_key = secrets.token_hex(32)       # str, 64 characters
url_key = secrets.token_urlsafe(32)   # str, 43 characters

print(len(raw_key), len(hex_key), len(url_key))  # 32 64 43

Choose by where the value will live. The 64-character hex string pastes cleanly into .env, a Helm value or a password manager entry, while the 43-character URL-safe string uses fewer characters but includes - and _, which some configuration formats do not like. Neither format is stronger than the other: both carry the same 32 random bytes, and the extra characters in hex are just a different encoding.

Why not use random or uuid for a JWT secret?

The random module uses the Mersenne Twister algorithm. Its output looks random but is fully determined by its internal state, and that state can be reconstructed from enough observed values. That is fine for shuffling quiz questions, not for the single value that lets anyone mint tokens for any user. Python's own documentation says the module should not be used for security purposes.

uuid.uuid4() is a better accidental choice because it uses the operating system random source, but it is designed as an identifier: it carries 122 random bits, has a fixed 36-character format and includes a version nibble. A JWT secret should be plain, full-entropy key material with a known length, which is what secrets returns.

# Do not do this: random is not a cryptographic generator.
import random

weak_secret = "".join(random.choices("0123456789abcdef", k=64))
print(len(weak_secret))  # 64 characters, but predictable

A quick self-check before you paste a secret anywhere: if you would not want the value to appear in a screenshot, generate it with secrets and keep it in an environment variable.

How do you sign and verify a JWT in Python?

PyJWT is the most widely used JWT library for Python. Install it with pip install "PyJWT>=2.11"; the 2.x series returns str tokens (1.x returned bytes), and versions 2.11 and later emit an InsecureKeyLengthWarning when an HMAC key is shorter than the RFC 7518 minimum, which is another reason the examples above generate 32 random bytes. Certificates and asymmetric algorithms such as RS256 need one extra dependency: pip install "PyJWT[crypto]". The examples in this section only need PyJWT; the PyJWT documentation lists the other supported algorithms and optional arguments.

from datetime import datetime, timedelta, timezone

import jwt

JWT_ALGORITHM = "HS256"
JWT_ISSUER = "example-api"


def create_access_token(user_id: int, secret: str) -> str:
    now = datetime.now(timezone.utc)
    claims = {
        "sub": str(user_id),
        "iss": JWT_ISSUER,
        "iat": now,
        "exp": now + timedelta(minutes=15),
    }
    return jwt.encode(claims, secret, algorithm=JWT_ALGORITHM)


def read_access_token(token: str, secret: str) -> dict:
    return jwt.decode(
        token,
        secret,
        algorithms=[JWT_ALGORITHM],
        issuer=JWT_ISSUER,
        options={"require": ["sub", "iss", "iat", "exp"]},
    )


if __name__ == "__main__":
    import secrets

    secret = secrets.token_hex(32)  # in production, load it from the environment
    token = create_access_token(42, secret)
    print(read_access_token(token, secret)["sub"])  # 42

Two habits keep this code safe. Always pass algorithms explicitly: without that list, a token can name a different algorithm and try to trick the verifier. And catch jwt.InvalidTokenError instead of a broad Exception, because an expired token, a bad signature, a wrong issuer and a missing claim all raise subclasses of that one class.

import jwt

try:
    claims = read_access_token(token, secret)
except jwt.InvalidTokenError:
    # Expired, wrong signature, wrong issuer or a missing required claim.
    claims = None

How do you load the JWT secret from an environment variable?

Hard-coding the secret in a Python module turns every clone, laptop, CI log and shared screen into a possible leak. Generate the value once, keep it in a .env file for local development, and inject it through your platform's environment in production. Use the same variable name in both places so the code does not branch by environment.

python3 -c "import secrets; print(secrets.token_hex(32))"

Paste the output into .env, and keep a committed example file that lists the names without the values.

# .env - local development only, never committed
JWT_SECRET=replace-with-the-64-character-value
JWT_ISSUER=example-api
# .env.example - committed, shows the keys without secrets
JWT_SECRET=
JWT_ISSUER=example-api
# .gitignore
.env
.env.*
!.env.example

Load the file with python-dotenv in development only (pip install python-dotenv), and let the platform provide the variable in production:

import os
from pathlib import Path

from dotenv import load_dotenv

# Local development only. In production the platform sets the variable.
load_dotenv(Path(__file__).with_name(".env"))


def load_jwt_secret() -> str:
    value = os.environ.get("JWT_SECRET", "").strip()
    if not value:
        raise RuntimeError(
            "JWT_SECRET is not set - copy .env.example to .env and fill it in"
        )
    if len(value.encode("utf-8")) < 32:
        raise RuntimeError("JWT_SECRET must be at least 32 bytes for HS256")
    return value


JWT_SECRET = load_jwt_secret()

The loader fails at import time, before the first request is served, and the length check catches a truncated or placeholder paste. Set the file permissions so other users on the host cannot read it:

chmod 600 .env

In production, do not ship the .env file at all. Put JWT_SECRET in the systemd service environment (EnvironmentFile=/etc/jwt-api/jwt.env, owned by the service user with mode 600), in a Docker secret mounted under /run/secrets/, or in a Kubernetes Secret referenced with secretKeyRef. All three keep the value out of the image and out of the repository. Whatever the source, never print the variable in logs or error pages, and remember that a value in shell history or in plain docker inspect output is already exposed.

Where does the secret go in Django and Flask?

Read the value from the environment when the application starts and hand it to the JWT library. In Django, keep it next to your other settings but load it from os.environ; with djangorestframework-simplejwt the key goes in the SIMPLE_JWT dictionary.

# settings.py
import os
from datetime import timedelta

SIMPLE_JWT = {
    "SIGNING_KEY": os.environ["JWT_SECRET"],
    "ALGORITHM": "HS256",
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
}

Do not reuse Django's SECRET_KEY for JWTs. It already signs sessions, password-reset links and framework messages, so rotation or a leak would take both systems down at once, and a separate key keeps each blast radius smaller. In Flask, the config name depends on the extension: Flask-JWT-Extended reads JWT_SECRET_KEY, while code that calls PyJWT directly can read any config name you like.

# app.py
import os

from flask import Flask

app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET"]  # Flask-JWT-Extended
app.config["JWT_ISSUER"] = os.environ.get("JWT_ISSUER", "example-api")

Both snippets read the same environment variable, so one deployment works for either framework, and the .env file above is enough for local tests. Whichever framework you use, keep the key out of the repository and out of any settings file that gets committed.

What about rotating the secret later?

A JWT secret is not a one-time value: it should be rotated on a schedule and immediately after any suspected exposure. The mechanics fit in a few sentences. Keep two keys during an overlap window, add a kid header to every token so a verifier knows which key to use, sign new tokens with the new key while still accepting tokens signed with the old one, and delete the old key after its last token has expired.

For a 15-minute access token, a 30 to 60 minute overlap is usually enough, while refresh tokens and server-side sessions need their own plan because they live longer. Order matters more than timing: start verifying with both keys before you start signing with the new one, otherwise visitors see random logouts for the length of one deployment.

Frequently asked questions

Where should the JWT secret go in Django or Flask?

Read it from an environment variable and keep it separate from the framework secret. In Django, load it in settings.py with os.environ and give it to your JWT library, for example SIMPLE_JWT = {"SIGNING_KEY": os.environ["JWT_SECRET"]}. Django's own SECRET_KEY already signs sessions and password-reset tokens, so reusing it for JWTs means one rotation breaks both systems. In Flask, set app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET"] for Flask-JWT-Extended, or app.config["JWT_SECRET"] if you call PyJWT yourself. Commit neither the value nor a default fallback.

Why can't a token_urlsafe value be used as a hex string?

secrets.token_urlsafe encodes random bytes with the URL-safe Base64 alphabet, so its output can contain uppercase letters, lowercase letters, digits, hyphens and underscores. bytes.fromhex() accepts only two hex digits per byte, so it raises ValueError as soon as it meets a letter such as g or z, a hyphen or an underscore. token_hex is the function that returns a hex string, and it is the only one of the three you can pass to bytes.fromhex(). If you are not decoding, nothing needs to change: PyJWT accepts a str key and encodes it as UTF-8 for you.

How do multiple processes or Gunicorn workers share one secret?

Generate the secret once, store it in the environment or a secret manager, and let every process read the same value when it starts. Gunicorn, uvicorn and uWSGI workers inherit the environment from the parent process, so they all see one JWT_SECRET. Do not call secrets.token_hex inside a module that each worker imports: every worker would get a different key, and a token signed by one worker would fail verification on the next request that lands on another. A development server that reloads on file changes is fine, because the key comes from .env rather than from the code.

What happens to tokens already issued when I rotate the secret?

They stop verifying as soon as the new secret is the only key you accept. To avoid that, run a two-key window: deploy code that verifies tokens with both the old and the new secret, switch signing to the new one, then remove the old one after the longest access-token lifetime plus a little clock skew has passed. Tokens signed with the old secret stay valid until their exp claim. Refresh tokens and server-side sessions have their own lifetime, so either plan the same overlap for them or revoke them deliberately.

Can I use random.randbytes(32) or uuid.uuid4() instead?

Not random: the random module is a Mersenne Twister, its output can be predicted after an attacker observes enough values, and the Python documentation marks it as unsuitable for security. uuid4 is a better accident because it uses the operating system random source, but it carries 122 random bits, has a fixed identifier format and was never designed as key material. Use secrets, which exists for exactly this job and returns the bytes or the encoded string your library needs.

Should I use a 64-byte secret if I sign with HS512?

RFC 7518 requires an HMAC key at least as long as the hash output, which means 32 bytes for HS256 and 64 bytes for HS512. PyJWT 2.11 and later emit an InsecureKeyLengthWarning for a key below that minimum, and you can make it raise InvalidKeyError by setting enforce_minimum_key_length to True in the decode options. A 32-byte key still works with HS512, but it gives less margin than the specification asks for, so use secrets.token_hex(32) with HS256, or secrets.token_hex(64) if you plan to move to HS512 later.

Generate a JWT secret key

For the full picture, start from the JWT secret key generator, then decode a JWT token to check the result.