Bird
Raised Fist0
FastAPIframework~20 mins

Testing authentication in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of testing authentication in a FastAPI application?
easy
A. To improve the app's UI design
B. To speed up the server response time
C. To verify that only authorized users can access protected routes
D. To check database connection speed

Solution

  1. Step 1: Understand authentication testing goal

    Authentication testing ensures users are properly verified before accessing certain parts of the app.
  2. Step 2: Identify the correct purpose

    Only authorized users should access protected routes, which is what authentication testing checks.
  3. Final Answer:

    To verify that only authorized users can access protected routes -> Option C
  4. Quick Check:

    Authentication testing = verify authorized access [OK]
Hint: Authentication tests check user access control only [OK]
Common Mistakes:
  • Confusing authentication with UI or performance testing
  • Thinking authentication tests improve speed
  • Mixing authentication with database tests
2. Which FastAPI tool is commonly used to simulate HTTP requests during authentication tests?
easy
A. HTTPServer
B. TestClient
C. RequestSimulator
D. AuthTester

Solution

  1. Step 1: Recall FastAPI testing utilities

    FastAPI provides TestClient to simulate HTTP requests in tests easily.
  2. Step 2: Match the tool to the name

    TestClient is the official tool; others are not part of FastAPI.
  3. Final Answer:

    TestClient -> Option B
  4. Quick Check:

    FastAPI request simulation = TestClient [OK]
Hint: Use TestClient to simulate requests in FastAPI tests [OK]
Common Mistakes:
  • Using non-existent tools like HTTPServer or AuthTester
  • Confusing TestClient with server components
  • Not importing TestClient from fastapi.testclient
3. Given this FastAPI test code snippet, what will be the response status code when accessing a protected route without credentials?
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

response = client.get('/protected')
print(response.status_code)
medium
A. 401
B. 404
C. 200
D. 500

Solution

  1. Step 1: Understand protected route behavior

    Protected routes require authentication; without credentials, access is denied.
  2. Step 2: Identify expected HTTP status code

    Unauthorized access returns 401 status code, not 200 (success) or 404 (not found).
  3. Final Answer:

    401 -> Option A
  4. Quick Check:

    Unauthorized access = 401 status [OK]
Hint: No credentials on protected route returns 401 Unauthorized [OK]
Common Mistakes:
  • Expecting 200 OK without authentication
  • Confusing 401 with 404 Not Found
  • Assuming server error 500 instead of auth error
4. Identify the error in this FastAPI authentication test code:
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

response = client.post('/login', json={'username': 'user', 'password': 'wrongpass'})
assert response.status_code == 200
medium
A. The TestClient import is incorrect
B. The client should use GET instead of POST
C. The JSON keys should be 'user' and 'pass' instead
D. The test expects status 200 even with wrong password

Solution

  1. Step 1: Analyze expected login response

    Wrong password should cause login failure, usually status 401 or 403, not 200.
  2. Step 2: Check test assertion correctness

    Asserting status 200 on wrong credentials is incorrect and will fail the test.
  3. Final Answer:

    The test expects status 200 even with wrong password -> Option D
  4. Quick Check:

    Wrong password should NOT return 200 [OK]
Hint: Wrong password login returns error, not 200 OK [OK]
Common Mistakes:
  • Assuming POST is wrong method for login
  • Using incorrect JSON keys for credentials
  • Misimporting TestClient
5. You want to test a FastAPI route that requires a valid JWT token in the Authorization header. Which approach correctly simulates an authenticated request in your test?
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

# Options:
# A) client.get('/secure', headers={'Authorization': 'Bearer validtoken'})
# B) client.get('/secure')
# C) client.get('/secure', json={'token': 'validtoken'})
# D) client.get('/secure', cookies={'Authorization': 'validtoken'})
hard
A. Send the token in Authorization header with 'Bearer ' prefix
B. Send no token and expect access
C. Send token in JSON body for GET request
D. Send token as a cookie named Authorization

Solution

  1. Step 1: Recall JWT token usage in HTTP requests

    JWT tokens are sent in the Authorization header with 'Bearer ' prefix for authentication.
  2. Step 2: Evaluate each option's correctness

    Sending the token in the Authorization header with 'Bearer ' prefix correctly simulates authentication. No token, JSON body for GET, or cookies will fail.
  3. Final Answer:

    Send the token in Authorization header with 'Bearer ' prefix -> Option A
  4. Quick Check:

    JWT token in Authorization header = Send the token in Authorization header with 'Bearer ' prefix [OK]
Hint: JWT tokens go in Authorization header with 'Bearer ' prefix [OK]
Common Mistakes:
  • Sending token in JSON body for GET requests
  • Omitting the 'Bearer ' prefix
  • Using cookies instead of headers for JWT
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard