Once a user has successfully authenticated, you can generate an access token to represent their identity. This token can be included in subsequent requests to verify their authorization. In this section, we’ll demonstrate how to generate access tokens using JWTs in FastAPI.
Creating an Access Token
Python
import jwt
from fastapi import Depends, HTTPException
from app.models import User
def create_access_token(data: dict):
token = jwt.encode(data, "your_secret_key", algorithm="HS256")
return token
@router.post("/login", response_model=Token)
async def login(user: Login, db: Session = Depends(get_db)):
db_user = await db.query(User).filter(User.email == user.email).first()
if not db_user or not verify_password(user.password, db_user.password):
raise HTTPException(status_code=401, detail="Incorrect username or password")
access_token = create_access_token({"sub": db_user.id})
return {"access_token": access_token}
Decoding and Verifying Access Tokens
Python
def decode_access_token(token: str):
try:
data = jwt.decode(token, "your_secret_key", algorithms=["HS256"])
return data
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
@router.get("/protected")
async def protected_route(request: Request):
token = request.headers.get("Authorization").split()[1]
data = decode_access_token(token)
user_id = data["sub"]
# ...
Terms:
- Token Expiration: Set an expiration time for access tokens to prevent unauthorized access.
- Refresh Tokens: Consider using refresh tokens to allow users to renew their access tokens without re-authenticating.
- Token Revocation: Implement a mechanism to revoke tokens if they are compromised.
- Security: Keep your secret key secret and use a strong algorithm for signing JWTs.
By following these steps, you can effectively generate and manage access tokens in your FastAPI application, protecting your API endpoints from unauthorized access.