0
0
FastAPIframework~20 mins

Testing authentication in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Authentication Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when an unauthenticated user accesses a protected route?

Consider a FastAPI app with a route protected by OAuth2 password bearer token authentication. What response does the client receive if no token is provided?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
    return {"message": "Access granted"}
AHTTP 401 Unauthorized with detail 'Not authenticated'
BHTTP 403 Forbidden with detail 'Not enough permissions'
CHTTP 200 OK with message 'Access granted'
DHTTP 500 Internal Server Error
Attempts:
2 left
💡 Hint

Think about what happens when the OAuth2PasswordBearer dependency does not find a token.

state_output
intermediate
2:00remaining
What is the value of 'user' after successful token validation?

Given a FastAPI dependency that decodes a JWT token and returns a user dictionary, what is the value of user inside the route after passing a valid token?

FastAPI
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

fake_users_db = {"alice": {"username": "alice", "email": "alice@example.com"}}

def get_current_user(token: str = Depends(oauth2_scheme)):
    # Simulate decoding token to username
    username = token
    user = fake_users_db.get(username)
    if not user:
        raise HTTPException(status_code=400, detail="Invalid user")
    return user

@app.get("/me")
async def read_users_me(user: dict = Depends(get_current_user)):
    return user
A{"username": "bob", "email": "bob@example.com"}
BNone
C{"username": "alice", "email": "alice@example.com"}
DRaises HTTPException with status 400
Attempts:
2 left
💡 Hint

Check what the token string is and how it maps to the fake user database.

📝 Syntax
advanced
2:00remaining
Which option correctly implements a FastAPI dependency to verify an API key header?

Choose the code snippet that correctly defines a dependency to check for an API key in the header X-API-Key and raises 403 if missing or invalid.

A
from fastapi import Header, HTTPException

def verify_api_key(x_api_key: str = Header):
    if x_api_key != "secret123":
        raise HTTPException(status_code=403, detail="Invalid API Key")
B
from fastapi import Header, HTTPException, status

def verify_api_key(x_api_key: str = Header(None)):
    if x_api_key != "secret123":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API Key")
C
from fastapi import Header, HTTPException, status

def verify_api_key(x_api_key: str = Header(...)):
    if x_api_key == "secret123":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API Key")
D
from fastapi import Header, HTTPException, status

def verify_api_key(x_api_key: str = Header(...)):
    if x_api_key != "secret123":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API Key")
Attempts:
2 left
💡 Hint

Remember that Header(...) means the header is required. Also check the status code and condition logic.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI test for authentication fail with 422 Unprocessable Entity?

Given this test code for a FastAPI endpoint requiring a token, why does the test fail with status 422 instead of 401?

FastAPI
from fastapi.testclient import TestClient

client = TestClient(app)

def test_protected_route():
    response = client.get("/protected")
    assert response.status_code == 401
AThe OAuth2PasswordBearer dependency expects the token in the Authorization header, but the test sends no header, causing validation error 422.
BThe test client automatically adds an invalid token causing 422 error.
CThe route does not require authentication, so 422 is returned by mistake.
DThe test is missing a JSON body, which is required by the route.
Attempts:
2 left
💡 Hint

Check how OAuth2PasswordBearer expects the token to be sent in requests.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of dependencies in FastAPI authentication testing?

When writing tests for FastAPI authentication, what is the main advantage of using dependency overrides?

AThey automatically generate valid tokens for testing protected routes.
BThey allow replacing real authentication logic with mock functions to simulate authenticated users without real tokens.
CThey disable authentication checks entirely during tests.
DThey enforce stricter validation rules on tokens during testing.
Attempts:
2 left
💡 Hint

Think about how to test routes without relying on real authentication mechanisms.