Tokens: Signing In with a JWT
After a sign-in, an API hands out a JWT, a signed token in three parts that PyJWT makes with jwt.encode and an exp claim and checks with jwt.decode, at POST /auth/token with the OAuth2 password form so the docs page's Authorize button works, and the caller sends it back in an Authorization header with every request.
Journeyman · FastAPI · REST API · Updated
After this lesson you can
- Make a JWT with jwt.encode and an exp claim, check it with jwt.decode, and explain its three parts and why it never holds a secret
- Sign a user in at POST /auth/token with OAuth2PasswordRequestForm, and read the bearer token each request sends back
Key takeaways
- After a sign-in, the API hands out a token, like a festival wristband, so the password crosses the network once and never again.
- A JWT is three parts joined by dots. The header and the payload are only base64url, so anyone can read them. The signature proves nobody changed them.
- jwt.encode signs the payload with the secret key, and jwt.decode checks the signature and the exp claim, raising an InvalidTokenError such as ExpiredSignatureError when either fails.
- POST /auth/token takes the form fields username and password, so the docs page's Authorize button can sign in. Its 401 sends the header WWW-Authenticate with the value Bearer.
- The secret key is long and random, read from an environment variable, and never written in the code.
Sign in to almost any app and stay signed in for the next hour: behind that, there's usually a token. Phone apps use them, single-page web apps use them, and so does every API you'll call with a key. This lesson gives Bright Minds Study Group's students one.
A wristband instead of a password
HTTP forgets. Each request arrives on its own, so after Sign-Up and Sign-In Routes, Maya would have to send her password with every request. That puts her password on the network again and again, and makes the server run a slow Argon2 check every time.
A music festival solves the same problem. The gate checks your ID once and puts a wristband on you. After that, every stage checks the wristband: it can't be faked, because only the festival can make one, and it stops working when the festival ends.
A JWT, a JSON Web Token (often read "jot"), is that wristband. It's three parts joined by dots (each read "dot"): a header saying how it was signed, a payload holding claims (facts such as who it's for and when it expires), and a signature that only the holder of the secret key can make.
Making and checking a token with PyJWT
The PyJWT package (import jwt) makes and checks tokens. sub, the subject, is who the token is for, as text. exp is when it expires, in seconds since 1970; 1924992000 is the start of 2031:
import jwt
SECRET_KEY = "change-me-to-a-long-random-secret"
token = jwt.encode({"sub": "1", "name": "Maya", "exp": 1924992000}, SECRET_KEY, algorithm="HS256")
print(token)
print(jwt.decode(token, SECRET_KEY, algorithms=["HS256"]))
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwibmFtZSI6Ik1heWEiLCJleHAiOjE5MjQ5OTIwMDB9.k_-7J2b4B3WtlXoXOEOVcwmSPqBChAS4HDdrxFooK-U
{'sub': '1', 'name': 'Maya', 'exp': 1924992000}
HS256 signs with one shared secret key. jwt.decode checks the signature and exp before it gives back the payload, and raises an InvalidTokenError when either fails:
import jwt
SECRET_KEY = "change-me-to-a-long-random-secret"
expired = jwt.encode({"sub": "1", "exp": 1700000000}, SECRET_KEY, algorithm="HS256")
try:
jwt.decode(expired, SECRET_KEY, algorithms=["HS256"])
except jwt.ExpiredSignatureError as error:
print("Expired:", error)
forged = jwt.encode({"sub": "1", "exp": 1924992000}, "a-guess-at-the-secret-key-123456", algorithm="HS256")
try:
jwt.decode(forged, SECRET_KEY, algorithms=["HS256"])
except jwt.InvalidTokenError as error:
print("Refused:", error)
Expired: Signature has expired
Refused: Signature verification failed
Anyone with the key can make tokens for any student, so the key is long and random, and it never goes in the code. The app reads it from an environment variable, and gives each token an hour:
SECRET_KEY = os.environ["JWT_SECRET"]
def make_token(student_id):
expires = datetime.now(timezone.utc) + timedelta(hours=1)
return jwt.encode({"sub": str(student_id), "exp": expires}, SECRET_KEY, algorithm="HS256")
PyJWT refuses a sub that isn't text, hence str(student_id), and warns about a key shorter than 32 characters.
Signing in at /auth/token
The sign-in route now answers with a token. It also moves to POST /auth/token and takes form fields instead of JSON, username and password, because that's what the OAuth2 standard's password sign-in sends, and what FastAPI's docs page sends. The username field holds Maya's email:
@router.post("/auth/token")
def sign_in(form: OAuth2PasswordRequestForm = Depends(), conn: sqlite3.Connection = Depends(get_db, scope="function")):
student = students_data.find_student_by_email(conn, form.username)
if student is None or not password_hash.verify(form.password, student["password_hash"]):
raise HTTPException(
status_code=401,
detail="The email or password is wrong.",
headers={"WWW-Authenticate": "Bearer"},
)
return {"access_token": make_token(student["id"]), "token_type": "bearer"}
Maya's password answers 200 with {"access_token": "eyJhbGciOi…", "token_type": "bearer"}. A wrong one answers 401, and the WWW-Authenticate header tells the caller how to sign in: with a bearer token. The HTTPException handler from One Error Shape for the Whole API passes the header on with problem(exc.status_code, exc.detail, headers=exc.headers), so the answer has the one shape and the header:
401 Unauthorized
www-authenticate: Bearer
{"status":401,"title":"Unauthorized","detail":"The email or password is wrong."}
Sending the token back
The token goes back with every request in the Authorization header, as Bearer and then the token: whoever bears it is let in. OAuth2PasswordBearer reads that header for a route, and adds an Authorize button to the docs page:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
@router.get("/me", response_model=StudentOut)
def me(token: str = Depends(oauth2_scheme), conn: sqlite3.Connection = Depends(get_db, scope="function")):
try:
student_id = int(jwt.decode(token, SECRET_KEY, algorithms=["HS256"])["sub"])
except jwt.InvalidTokenError:
student_id = None
student = students_data.get_student(conn, student_id)
if student is None:
raise HTTPException(
status_code=401,
detail="The token isn't valid or has expired.",
headers={"WWW-Authenticate": "Bearer"},
)
return student
get_student finds a student by id, without the hash. A bad token gives no id, and no id, or the id of a student who has since been deleted, finds nobody: both answer 401. GET /me with Maya's token answers {"id":1,"name":"Maya","email":"maya@example.com"}. With no header at all, OAuth2PasswordBearer answers 401 with the detail "Not authenticated" before the route runs. On the docs page, Authorize asks for a username and password, signs in at /auth/token, and from then on sends the token with every Try it out. Requiring a Signed-In User turns this check into a dependency that any route can use.
Do it: read what's inside a study group token
A token's header and payload aren't locked. They're only base64url, a way of writing any bytes with letters, digits, - and _, so anyone who has a token can read them. That's why a token never holds a password or anything else secret. Prove it by reading a token without the key.
token: a JWT, as text, such as one the study group's/auth/tokengave out.
Your job:
- Write
read_payload(token), which returns the token's payload as a dictionary. - The payload is the middle part: the text between the two dots.
base64.urlsafe_b64decodedecodes it, but only when its length is a multiple of 4. JWTs leave off the=signs that pad it, so add=to the end until the length is a multiple of 4 (none when it already is).json.loadsturns the decoded bytes into a dictionary.
Worked through: for Maya's token above, the middle part is eyJzdWIiOiIxIiwibmFtZSI6Ik1heWEiLCJleHAiOjE5MjQ5OTIwMDB9, 56 characters, already a multiple of 4. It decodes to {"sub":"1","name":"Maya","exp":1924992000}, so read_payload returns {"sub": "1", "name": "Maya", "exp": 1924992000}.
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
A token lets a student sign in once and stay signed in for an hour, and because anyone can read its payload, you now know the one rule that keeps it safe: it carries who someone is, never a secret.