OAuth2 Password Bearer
First, we’ll useOAuth2PasswordBearer to tell FastAPI how authentication works in your API.
Basic Token Extraction
Here’s the simplest possible OAuth2 implementation:1
Create the OAuth2 scheme
OAuth2PasswordBearer(tokenUrl="token") tells FastAPI:- Tokens are obtained from the
/tokenendpoint - The client should send tokens in the
Authorization: Bearer <token>header
2
Use as a dependency
token: str = Depends(oauth2_scheme) tells FastAPI to:- Check for the
Authorizationheader - Verify it starts with
Bearer - Extract the token part
- Pass it to your function
3
Automatic OpenAPI integration
Visit
/docs and you’ll see an “Authorize” button. FastAPI automatically added it based on your security scheme!How OAuth2PasswordBearer Works
When you call the/items/ endpoint:
- Check the
Authorizationheader exists - Verify it starts with
Bearer - Extract
my_secret_token - Pass it to your function as the
tokenparameter
What if the Header is Missing?
If theAuthorization header is missing or invalid, FastAPI automatically returns:
401 Unauthorized and header WWW-Authenticate: Bearer.
Creating the Login Endpoint
Now let’s create the/token endpoint that issues tokens. We’ll use OAuth2PasswordRequestForm to collect the username and password:
Understanding OAuth2PasswordRequestForm
TheOAuth2PasswordRequestForm is a dependency class that extracts form data from the request:
str
required
The username field (required by OAuth2 spec)
str
required
The password field (required by OAuth2 spec)
str
Optional scopes separated by spaces (e.g., “items:read items:write”)
str
Should be “password” according to OAuth2 spec (but this form is lenient)
str
Optional client ID
str
Optional client secret
Testing the Login
You can test the login endpoint with cURL:The OAuth2 specification requires using form data (not JSON) for the token endpoint. FastAPI handles this automatically with
OAuth2PasswordRequestForm.Testing in the Docs
Now visit/docs and try the authentication flow:
1
Click Authorize
Click the “Authorize” button at the top right
2
Enter credentials
Enter username
johndoe and password secret3
Authorize
Click “Authorize” to save the credentials
4
Test protected endpoints
Now try calling
/items/ - it will automatically include your token!What We’ve Built (and What’s Missing)
What Works
✅ OAuth2 password flow ✅ Token endpoint that validates credentials ✅ Protected endpoints that require authentication ✅ Automatic OpenAPI documentation with “Authorize” buttonWhat’s Still Missing
In the next sections, we’ll add:- Proper user retrieval and validation
- Real JWT tokens with expiration
- Password hashing with industry-standard algorithms
The Token Response Format
According to OAuth2 spec, the token endpoint must return JSON with:token_type must be "bearer" (lowercase) for OAuth2 password flow.
Next Steps
Now that you understand the basic OAuth2 flow, let’s build a proper dependency to get the current authenticated user:Get Current User
Learn how to create a reusable dependency that validates tokens and returns user information