Create a JWT Token
Add a function that generates signed JSON Web Tokens for authenticated users
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The problem tokens solve
After a user logs in with the correct password, the server needs to give them something to send with future requests. Without this, the user would have to send their password with every single request.
That something is a JSON Web Token (JWT). A JWT contains two key parts:
- Payload: the data you want to carry — in this case, the user's email
- Signature: cryptographic proof that the server created this token
The server signs the token with a secret key. On future requests, the server checks the signature. If the signature matches, the token is genuine and has not been tampered with.
Expiration and security
You set the expiration time — in this course, 30 minutes. If someone steals a token, it stops working after that window. The user simply logs in again to get a fresh one. Production applications choose their expiration based on security needs: 15 minutes for banking, hours or days for less sensitive applications.
The SECRET_KEY is a random string that the server uses to sign and verify tokens — it works like a password for your entire application. The server combines the payload with this key to produce the signature. When a token comes back in a request, the server uses the same key to check that the signature is valid.
Anyone who knows your secret key can create tokens that your server will trust. In production, set it as an environment variable with a long random string (32+ characters). The "change-me-in-production" default in the code works for local development only.
Instructions
Add JWT token creation to auth.py.
- Add three constants below the imports:
SECRET_KEY = os.getenv("SECRET_KEY", "change-me-in-production")— reads the secret key from an environment variable, falling back to a default for local developmentALGORITHM = "HS256"— the signing algorithm. HS256 (HMAC with SHA-256) is the most common choice for JWTACCESS_TOKEN_EXPIRE_MINUTES = 30— how long each token stays valid before the user must log in again
- Define a function called
create_access_tokenthat takes anemailstring and returns a string. - Inside the function, calculate when the token should expire:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)— this takes the current time in UTC and adds 30 minutes. - Build the payload dictionary:
payload = {"sub": email, "exp": expire}—"sub"(subject) is the standard JWT field for identifying who the token belongs to, and"exp"is the standard field for expiration time. - Return
jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)— this combines the payload and your secret key to produce a signed token string that the server can verify later.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding