FastAPI for AI Engineers - Part 7: Protecting Routes with JWT Tokens FastAPI developers can protect routes using JWT tokens by integrating OAuth2PasswordBearer and a token verification function. The approach extracts the token from the Authorization header, decodes it to identify the user, and uses a dependency to restrict access to authenticated users only. In the previous article, we learned how to: However, generating a token alone doesn't secure an application. Anyone can still access endpoints unless we verify the token before granting access. Today we'll learn how FastAPI identifies users from JWT tokens and protects routes from unauthorized access. Do check out the previous post to understand this: Suppose we have: python @app.get "/profile" def get profile : return {"message": "My profile"} Anyone can access this endpoint. There is no verification of: Login ↓ Generate JWT ↓ Store JWT ↓ Send JWT with Request ↓ Verify JWT ↓ Allow Access OAuth2PasswordBearer is a class provided by FastAPI to handle security and authentication using OAuth2 with the Password flow and Bearer tokens. This class simplifies the process of implementing secure authentication in your FastAPI application. To use OAuth2PasswordBearer, you need to create an instance of it and pass the tokenUrl parameter, which specifies the URL where the client will send the username and password to obtain a token. python from fastapi.security import OAuth2PasswordBearer oauth2 scheme = OAuth2PasswordBearer tokenUrl="login" When a request arrives: Authorization: Bearer eyJhbGc... FastAPI automatically extracts the token. python from jose import jwt from jose import JWTError def verify token token: str : try: payload = jwt.decode token, SECRET KEY, algorithms= ALGORITHM username = payload.get "sub" return username except JWTError: return None JWT contains: { "sub": "suman", "exp": ... } We extract the username from "sub". This is the most important concept. python from fastapi import Depends def get current user token: str = Depends oauth2 scheme : username = verify token token if username is None: raise Exception "Invalid token" return username Every protected endpoint will use: Depends get current user This ensures that users who have registered and who's JWT token has been verified only they have access to the protected route. python @app.get "/profile" def get profile current user: str = Depends get current user : return { "message": f"Welcome {current user}" } Now: Valid Token When access is granted as JWT token matches { "message": "Welcome suman" } Invalid Token Access not granted { "detail": "Could not validate credentials" } User Login ↓ JWT Token Generated ↓ Token Sent in Request ↓ FastAPI Extracts Token ↓ JWT Verification ↓ Current User Identified ↓ Protected Route Access Today we learned: In the next article, we'll move beyond authentication and implement Role-Based Access Control RBAC , allowing different users to have different permissions.