What is JWT?
A JSON Web Token (JWT) is a compact, self-contained
token that proves who you are. Instead of sending
your password with every request, you log in once,
get a token, and use that token for all future requests.
How It Works
- User sends email + password to
/auth/login - Server verifies credentials
- Server generates a JWT containing user ID
- User sends that JWT with every protected request
- Server verifies the token and grants access
Generating the Token
def create_token(user_id: int, email: str):
payload = {
"user_id": user_id,
"email": email,
"exp": datetime.utcnow() + timedelta(hours=24)
}
return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
The token contains user_id, email and an expiry time.
It's signed with a secret key, tamper with it and
it becomes invalid.
Verifying the Token
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token has expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
The Protected Route
@app.get("/protected")
def protected_route(current_user: dict = Depends(verify_token)):
return {
"message": "You have access!",
"user": current_user
}
Depends(verify_token) runs the token check before
the route logic. No valid token = no access.
Postman Tests
Signup
Login - JWT token returned
Protected route - No token - 401
Protected route - With token - Success
Lessons Learned
JWT is stateless — the server doesn't store sessions.
The token itself contains everything needed to
identify the user. This is why it scales so well
in distributed systems.
Day 16 done. 14 more to go.




Top comments (0)