Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Bearer Token Handling with FastAPI
📖 Scenario: You are building a simple API that requires users to provide a bearer token to access protected data. This is common in real-world apps where security matters, like accessing your bank info or private messages.
🎯 Goal: Create a FastAPI app that checks for a bearer token in the request header and allows access only if the token matches a preset secret token.
📋 What You'll Learn
Create a FastAPI app instance called app
Define a secret token string variable called SECRET_TOKEN with value "mysecrettoken123"
Create a dependency function called verify_token that extracts the bearer token from the Authorization header
Check if the token matches SECRET_TOKEN and raise HTTPException with status 401 if it does not
Create a GET endpoint /protected that uses verify_token as a dependency and returns a JSON message {"message": "Access granted"}
💡 Why This Matters
🌍 Real World
APIs often require secure access control using bearer tokens to protect user data and resources.
💼 Career
Understanding bearer token handling is essential for backend developers working on secure web services and APIs.
Progress0 / 4 steps
1
Create FastAPI app and secret token
Import FastAPI from fastapi. Create a FastAPI app instance called app. Create a string variable called SECRET_TOKEN and set it to "mysecrettoken123".
FastAPI
Hint
Remember to import FastAPI first, then create the app and the secret token variable exactly as named.
2
Create token verification dependency
Import Depends, HTTPException, and status from fastapi. Import Header from fastapi. Define a function called verify_token that takes authorization: str | None = Header(default=None). Inside, check if authorization is None or does not start with "Bearer ". If so, raise HTTPException with status code status.HTTP_401_UNAUTHORIZED and detail "Invalid or missing token". Extract the token string after "Bearer " and check if it equals SECRET_TOKEN. If not, raise the same HTTPException. Return True if token is valid.
FastAPI
Hint
Use the Header parameter to get the Authorization header. Check for the 'Bearer ' prefix and compare the token to SECRET_TOKEN.
3
Create protected GET endpoint
Create a GET endpoint /protected using @app.get("/protected"). Add a parameter token: bool = Depends(verify_token) to use the token verification dependency. Return a dictionary {"message": "Access granted"} from the endpoint function.
FastAPI
Hint
Use Depends to call verify_token in the endpoint parameters. Return the success message as a dictionary.
4
Add CORS middleware for cross-origin requests
Import CORSMiddleware from fastapi.middleware.cors. Add CORS middleware to app with allow_origins=["*"], allow_credentials=True, allow_methods=["*"], and allow_headers=["*"]. This enables the API to be accessed from any website during development.
FastAPI
Hint
Use app.add_middleware with CORSMiddleware and set all allow options to "*" or True as shown.
Practice
(1/5)
1. What is the main purpose of using a Bearer token in FastAPI?
easy
A. To serve static files efficiently
B. To format JSON responses automatically
C. To speed up database queries
D. To securely identify and authorize API requests
Solution
Step 1: Understand Bearer token role
Bearer tokens are used to prove the client has permission to access protected routes.
Step 2: Identify purpose in FastAPI
FastAPI uses Bearer tokens to check authorization before allowing access to API endpoints.
Final Answer:
To securely identify and authorize API requests -> Option D
Quick Check:
Bearer token = Authorization [OK]
Hint: Bearer tokens are for security and access control [OK]
Common Mistakes:
Confusing token with response formatting
Thinking token speeds up database
Assuming token serves static files
2. Which FastAPI class is used to extract a Bearer token from the Authorization header?
easy
A. OAuth2PasswordBearer
B. HTTPBasicCredentials
C. OAuth2PasswordRequestForm
D. APIKeyHeader
Solution
Step 1: Recall FastAPI token extraction classes
OAuth2PasswordBearer is designed to read Bearer tokens from the Authorization header.
Step 2: Match class to Bearer token usage
OAuth2PasswordRequestForm is for form data, HTTPBasicCredentials is for basic auth, APIKeyHeader is for API keys, so only OAuth2PasswordBearer fits Bearer tokens.
5. You want to protect a FastAPI route so only requests with the exact Bearer token "secret123" are allowed. Which code snippet correctly implements this?
hard
A. async def protected_route(token: str = Depends(oauth2_scheme)):
if token == None:
return {"message": "Access granted"}
raise HTTPException(status_code=401, detail="Unauthorized")
B. async def protected_route(token: str = Depends(oauth2_scheme)):
if token != "secret123":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"message": "Access granted"}
C. async def protected_route(token: str):
if token == "secret123":
return {"message": "Access granted"}
raise HTTPException(status_code=403, detail="Forbidden")
D. async def protected_route(token: str = Depends(oauth2_scheme)):
if token == "Bearer secret123":
return {"message": "Access granted"}
raise HTTPException(status_code=401, detail="Unauthorized")
Solution
Step 1: Use OAuth2PasswordBearer dependency
We must use Depends(oauth2_scheme) to extract the token from the Authorization header.
Step 2: Check token value correctly
The token string is just the token without 'Bearer ' prefix, so compare directly to "secret123" and raise 401 if not matching.
Final Answer:
async def protected_route(token: str = Depends(oauth2_scheme)):
if token != "secret123":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"message": "Access granted"} -> Option B
Quick Check:
Compare token string directly to "secret123" [OK]
Hint: Compare token string directly, no 'Bearer ' prefix included [OK]
Common Mistakes:
Comparing token to 'Bearer secret123' including prefix