Create JWT Token
NotesWe could evolve the previous API, but for clarity here we’ll add a new route for generating a JWT token.
There is another package to install to help us achieve this, PyJWT:
pip install pyjwtAdd it to the non_ver_reqs.txt file:
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillow
captcha
pwdlib[argon2]
pyjwtAnd freeze the requirements:
pip freeze > requirements.txtEarlier versions of this guide used python-jose. Like the FastAPI documentation, this guide now uses PyJWT, which is actively maintained and is imported simply as jwt.
Add some new settings. The secret key signs every token: anyone who knows it can create tokens that log in as any user, so it must be long, random and secret. CONF_AUTH_EXPIRE_MINUTES is how long a login lasts before the user has to log in again:
import pathlib
import secrets # NEW
from pydantic import Field # NEW
from pydantic_settings import BaseSettings, SettingsConfigDict # Set CONF_AUTH_SECRET_KEY in .env: the random default changes every restart
CONF_AUTH_SECRET_KEY: str = Field(default_factory=lambda: secrets.token_hex(32)) # NEW
CONF_AUTH_ALGORITHM: str = "HS256" # NEW
CONF_AUTH_EXPIRE_MINUTES: int = 60 # NEW
CONF_AUTH_COOKIE_SECURE: bool = True # NEWThe default secret key is generated randomly each time the application starts. That’s safe, because there’s no real secret sitting in settings.py and version control, but every restart logs everyone out, and if you run several workers they’d each have a different key. So generate a key once:
python -c "import secrets; print(secrets.token_hex(32))"And put it in your .env file (a different one for each environment):
CONF_AUTH_SECRET_KEY=paste-the-generated-key-hereCONF_AUTH_COOKIE_SECURE is used in the next section.
Still working in auth_apis.py, import datetime, uuid and jwt, plus settings for the new settings and BaseModel for the response:
import datetime # NEW
import uuid # NEW
import jwt # NEW
from pydantic import BaseModel # NEW
from config.settings import settings # NEWAdd a new function for creating a JWT access token, which uses the secret key and algorithm settings:
def create_access_token_api(user_id: uuid.UUID) -> str:
now = datetime.datetime.now(datetime.UTC)
payload = {
"sub": str(user_id),
"iat": now,
"exp": now + datetime.timedelta(minutes=settings.CONF_AUTH_EXPIRE_MINUTES),
}
return jwt.encode(payload, settings.CONF_AUTH_SECRET_KEY, algorithm=settings.CONF_AUTH_ALGORITHM)The token’s subject (sub) is the user’s id. It’s better than the email address, which the user might change. iat (“issued at”) and exp (expiry) are standard claims: PyJWT converts the datetimes to timestamps, and when decoding, rejects the token automatically once exp has passed.
Add a model for the response, and a new route called login_for_token_api to authenticate a user and return an access token. It replaces the validate_user_with_password_api route from the previous page, which you can remove:
class Token(BaseModel):
access_token: str
token_type: str@router.post('/auth/token')
def login_for_token_api(form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
session: Session = Depends(get_session_db)) -> Token:
user = authenticate_user_api(form_data.username, form_data.password, session)
if not user or not user.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"})
return Token(access_token=create_access_token_api(user.id), token_type="bearer")The login_for_token_api route works just like the validation route, only this time it returns a token, in the standard OAuth2 shape that tools like Swagger understand. Users who have been deactivated (is_active is False) can’t log in.
Run and test the application again, logging in with the example user jsmith@email.com and password changeme, and if successful you should receive a JWT token, for example:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1NGJjZDA0My01MzQ1LTRmYTItYmIxMy1mY2M5ZjY4Y2YyMWMiLCJpYXQiOjE3OTYyMjAwMDAsImV4cCI6MTc5NjIyMzYwMH0.wAUWmnpADFt1b2UKLKtZWGjpPPI8LQFh9qORtbd9gew",
"token_type": "bearer"
}You can visit https://jwt.io/ and examine the token, which shows the sub, iat and exp claims. (This example was signed with the secret example-secret, which you can enter on jwt.io to check the signature.)