How to Use OAuth2PasswordBearer in FastAPI for Token Authentication
Use
OAuth2PasswordBearer in FastAPI to declare a token URL and extract the bearer token from requests automatically. It works as a dependency that you add to your path operations to enforce OAuth2 password flow authentication.Syntax
The OAuth2PasswordBearer class is initialized with the tokenUrl parameter, which is the URL where clients get the token. You then use it as a dependency in your path operation functions to get the token string from the Authorization header.
tokenUrl: URL path for token retrieval (e.g.,/token).- Dependency injection: use it as a parameter in your endpoint function to receive the token.
python
from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") async def read_items(token: str = oauth2_scheme): return {"token": token}
Example
This example shows a FastAPI app with a /token endpoint to simulate token creation and a protected /users/me endpoint that requires a valid token using OAuth2PasswordBearer. The token is extracted automatically from the Authorization header.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") @app.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): # This is a dummy check; in real apps, verify username and password if form_data.username != "user" or form_data.password != "pass": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) return {"access_token": "fake-token-for-user", "token_type": "bearer"} @app.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): # Here you would verify the token and get user info if token != "fake-token-for-user": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return {"username": "user", "token": token}
Output
POST /token with form data username=user&password=pass returns {"access_token":"fake-token-for-user","token_type":"bearer"}
GET /users/me with header Authorization: Bearer fake-token-for-user returns {"username":"user","token":"fake-token-for-user"}
Common Pitfalls
- Not setting the correct
tokenUrlinOAuth2PasswordBearercauses client confusion. - Forgetting to include
Depends(oauth2_scheme)in your endpoint parameters means the token won't be extracted. - Not validating the token after extraction leads to insecure endpoints.
- Using
OAuth2PasswordBearerwithout implementing the token endpoint (/token) breaks the OAuth2 flow.
python
from fastapi import Depends from fastapi.security import OAuth2PasswordBearer # Wrong: missing tokenUrl # oauth2_scheme = OAuth2PasswordBearer() # Correct: oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") # Wrong: not using Depends, token won't be extracted # async def endpoint(token: str): # pass # Correct: async def endpoint(token: str = Depends(oauth2_scheme)): pass
Quick Reference
OAuth2PasswordBearer Cheat Sheet:
OAuth2PasswordBearer(tokenUrl="/token"): Declare token URL.- Use as dependency:
token: str = Depends(oauth2_scheme). - Extracts token from
Authorization: Bearer <token>header. - Requires a token endpoint to issue tokens.
- Validate token manually after extraction.
Key Takeaways
Use OAuth2PasswordBearer with the tokenUrl parameter to specify where clients get tokens.
Add OAuth2PasswordBearer as a dependency to your endpoints to extract bearer tokens automatically.
Always implement and secure the token endpoint that issues tokens to clients.
Validate the extracted token in your endpoint logic to protect resources.
Common mistakes include missing Depends usage and not setting tokenUrl correctly.