Set Up Token Extraction
Exit

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 Authorization header 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.

  1. Create oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") — place it below the ACCESS_TOKEN_EXPIRE_MINUTES constant. This single line tells FastAPI how to extract the token from every incoming request's Authorization header.