Set Up Token Extraction
Add the OAuth2 scheme that reads JWT tokens from the Authorization header
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
One line that handles the Authorization header
OAuth2PasswordBearer is a class from FastAPI's security module. When you create an instance and use it as a dependency, it does three things automatically:
- Reads the
Authorizationheader from the incoming request - Checks that the header value starts with
Bearer - Returns just the token string — everything after
Bearer
If the Authorization header is missing entirely, FastAPI returns a 401 response immediately. Your endpoint code never runs.
Notice that the starter code now includes several new imports. These prepare auth.py for the verification function you will write in the next chapter: Annotated and Depends for dependency injection, HTTPException for error responses, JWTError for catching decoding failures, and Session, select, and get_session for database access.
Instructions
Add the OAuth2 scheme to auth.py.
- Create
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")— place it below theACCESS_TOKEN_EXPIRE_MINUTESconstant. This single line tells FastAPI how to extract the token from every incoming request'sAuthorizationheader.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding