Categories
Tags
30days AI ai backend blog blogging booking burnout career chatbot cms coding design development devops django docker email express fastapi flight Flight Booking System full stack full-stack gmail GPT-3 interviews journey LinkedIn MERN mongodb NextJS nextjs notion OpenAI openai planning portfolio programming project python react ReactJS search sendgrid smtp software software development tailwind
304 words
2 minutes
Day 18 of 30 Days of FastAPI - Identifying the Current User — From Tokens to Objects
Today, we are putting our security tools to work by identifying the Current User. It’s one thing to have a valid token; it’s another to know exactly who is making the request. We build the dependency that decodes the JWT, finds the user in the database, and makes the user object available to any route that needs it. We’ve hashed passwords and issued JWTs; now we need to turn those JWTs back into User objects.

1. The get_current_user Dependency
This is the heart of your security. It acts as a gatekeeper for your protected routes.
from jose import JWTError, jwt
from fastapi import Depends, HTTPException, status
from .database import get_db
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# 1. Decode the Token
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# 2. Fetch User from DB
user = db.query(models.User).filter(models.User.username == username).first()
if user is None:
raise credentials_exception
return user
2. Using the Dependency in Routes
Now, protecting a route is a one-liner. You don’t have to write any decoding logic in your actual business functions.
@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
return current_user

3. Why Dependency Chaining is a Superpower
FastAPI handles the “tree” of requirements for you. When a request hits /users/me:
- It sees it needs
get_current_user. get_current_userneedsoauth2_scheme(the token) andget_db.- FastAPI resolves all of them in order and passes the final
userobject to your function.
🛠️ Implementation Checklist
- Created the
get_current_userfunction. - Integrated JWT decoding logic and database lookup.
- Added
Annotatedfor cleaner dependency syntax. - Verified that
/users/mereturns the correct user profile when provided a valid token. - Confirmed that an expired or tampered token results in a
401 Unauthorized.
📚 Resources
- Official Docs: FastAPI Security - Get Current User
- Book: FastAPI: Modern Python Web Development (Chapter 7: Finalizing Authentication).
Day 18 of 30 Days of FastAPI - Identifying the Current User — From Tokens to Objects
https://beyond400.vercel.app/posts/fastapi-18/

