Bird
0
0
FastAPIframework~20 mins

Bearer token handling in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Bearer Token Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a valid bearer token is provided?

Consider this FastAPI endpoint that requires a bearer token for access. What will be the response if the token is valid?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

app = FastAPI()
security = HTTPBearer()

@app.get("/secure-data")
async def secure_data(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.scheme != "Bearer" or credentials.credentials != "validtoken123":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    return {"message": "Access granted"}
A{"message": "Access granted"}
B{"detail": "Invalid token"}
CHTTPException with status code 403
DEmpty response with status code 200
Attempts:
2 left
💡 Hint

Check the condition that validates the token and what the function returns if the token matches.

📝 Syntax
intermediate
1:30remaining
Which option correctly extracts the bearer token from the Authorization header?

Given a FastAPI dependency to extract a bearer token, which code snippet correctly retrieves the token string?

FastAPI
from fastapi import Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

security = HTTPBearer()

def get_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    # Extract token here
    pass
Areturn credentials.credentials
Breturn credentials.token
Creturn credentials.auth
Dreturn credentials.scheme
Attempts:
2 left
💡 Hint

Look at the attributes of HTTPAuthorizationCredentials to find the token string.

🔧 Debug
advanced
2:30remaining
Why does this FastAPI endpoint always raise 401 Unauthorized even with a valid token?

Review the code below. The endpoint should accept a bearer token 'secrettoken' but always returns 401 Unauthorized. What is the cause?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

app = FastAPI()
security = HTTPBearer()

@app.get("/data")
async def get_data(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.scheme != "Bearer" or credentials.credentials != "secrettoken":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
    return {"data": "secret info"}
AHTTPBearer() is not imported correctly
BThe scheme comparison is case-sensitive; 'bearer' should be 'Bearer'
CThe token string 'secrettoken' is incorrect
DDepends() is missing in the function parameter
Attempts:
2 left
💡 Hint

Check the exact string used to compare the scheme in the Authorization header.

state_output
advanced
2:00remaining
What is the response when no Authorization header is sent?

Given this FastAPI endpoint using HTTPBearer, what response does the client receive if the Authorization header is missing?

FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBearer

app = FastAPI()
security = HTTPBearer()

@app.get("/info")
async def info(credentials = Depends(security)):
    return {"token": credentials.credentials}
AHTTP 403 Forbidden error
BHTTP 200 OK with token value None
CEmpty JSON response {}
DHTTP 401 Unauthorized error
Attempts:
2 left
💡 Hint

Consider how HTTPBearer behaves when no Authorization header is provided.

🧠 Conceptual
expert
3:00remaining
Which statement best describes the role of HTTPBearer in FastAPI?

Choose the most accurate description of what HTTPBearer does in FastAPI applications.

AIt automatically authenticates the user and sets user info in the request context
BIt extracts and validates the bearer token from the Authorization header and raises 401 if missing or invalid
CIt only extracts the bearer token from the Authorization header but does not validate it
DIt encrypts the bearer token before sending it to the server
Attempts:
2 left
💡 Hint

Think about whether HTTPBearer checks token correctness or just extracts it.