Bird
0
0
FastAPIframework~10 mins

Bearer token handling in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Bearer token handling
Client sends request with Authorization header
Server reads Authorization header
Check if header starts with 'Bearer '
Extract token
Validate token
If valid: allow access
If invalid: reject request
The server checks the Authorization header for a Bearer token, extracts it, validates it, and then allows or denies access.
Execution Sample
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

app = FastAPI()
security = HTTPBearer()

@app.get("/secure")
async def secure_route(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    if token != "validtoken":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    return {"message": "Access granted"}
This FastAPI code checks for a Bearer token, validates it, and returns access granted or unauthorized.
Execution Table
StepActionAuthorization HeaderToken ExtractedToken Valid?Result
1Client sends requestBearer validtokenRequest received
2Server reads headerBearer validtokenHeader read
3Check header starts with 'Bearer 'Bearer validtokenYesProceed
4Extract tokenBearer validtokenvalidtokenToken extracted
5Validate tokenBearer validtokenvalidtokenYesAccess granted
6Return response{"message": "Access granted"}
7Client sends requestBearer invalidtokenRequest received
8Server reads headerBearer invalidtokenHeader read
9Check header starts with 'Bearer 'Bearer invalidtokenYesProceed
10Extract tokenBearer invalidtokeninvalidtokenToken extracted
11Validate tokenBearer invalidtokeninvalidtokenNoRaise 401 Unauthorized
12Return responseHTTP 401 Unauthorized
💡 Execution stops after returning response based on token validity.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 10After Step 11
Authorization HeaderBearer validtokenBearer validtokenBearer invalidtokenBearer invalidtoken
Token Extractedvalidtokenvalidtokeninvalidtokeninvalidtoken
Token Valid?YesNo
ResultAccess granted401 Unauthorized
Key Moments - 3 Insights
Why do we check if the header starts with 'Bearer ' before extracting the token?
Because the Authorization header might contain other schemes like 'Basic'. Checking ensures we only process Bearer tokens, as shown in steps 3 and 9 of the execution_table.
What happens if the token is invalid?
The server raises an HTTP 401 Unauthorized error and stops processing, as seen in steps 11 and 12 in the execution_table.
Why do we extract the token from the header instead of using the whole header value?
The header includes the word 'Bearer' plus the token. We only need the token part to validate it, as shown in steps 4 and 10 where the token is extracted.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the token extracted at step 10?
Avalidtoken
Binvalidtoken
CBearer invalidtoken
DNo token extracted
💡 Hint
Check the 'Token Extracted' column at step 10 in the execution_table.
At which step does the server decide the token is invalid?
AStep 5
BStep 9
CStep 11
DStep 12
💡 Hint
Look at the 'Token Valid?' and 'Result' columns in the execution_table for when 'No' appears.
If the Authorization header was 'Basic abc123', what would happen?
AToken extracted and validated
BRequest rejected because header does not start with 'Bearer '
CAccess granted automatically
DServer crashes
💡 Hint
Refer to the decision at step 3 and 9 about checking the header prefix.
Concept Snapshot
Bearer token handling in FastAPI:
- Client sends Authorization header: 'Bearer <token>'
- Server checks header starts with 'Bearer '
- Extract token part after 'Bearer '
- Validate token (e.g., compare to expected value)
- If valid, allow access; if not, raise 401 Unauthorized
- Use HTTPBearer and HTTPAuthorizationCredentials for easy handling
Full Transcript
In Bearer token handling with FastAPI, the client sends a request with an Authorization header containing the token prefixed by 'Bearer '. The server reads this header and first checks if it starts with 'Bearer '. If it does, the server extracts the token part after 'Bearer ' and validates it. If the token matches the expected value, the server grants access and returns a success message. If the token is invalid or the header does not start with 'Bearer ', the server rejects the request with a 401 Unauthorized error. This process ensures secure access control using tokens. The FastAPI HTTPBearer security class helps manage this flow easily by extracting and validating tokens automatically.