0
0
FastAPIframework~5 mins

Testing authentication in FastAPI

Choose your learning style9 modes available
Introduction

Testing authentication helps make sure only the right users can access your app. It checks if login and security work correctly.

When you want to check if users can log in with correct credentials.
When you want to verify that unauthorized users cannot access protected pages.
When you want to test token or session-based login flows.
When you want to make sure logout works and ends the user session.
When you want to catch bugs in your security code before users see them.
Syntax
FastAPI
from fastapi.testclient import TestClient
from your_app import app

client = TestClient(app)

response = client.post('/login', data={'username': 'user', 'password': 'pass'})
assert response.status_code == 200
assert 'access_token' in response.json()

Use TestClient from FastAPI to simulate requests to your app.

Check response status and content to confirm authentication success or failure.

Examples
Test successful login returns a token.
FastAPI
response = client.post('/login', data={'username': 'alice', 'password': 'secret'})
assert response.status_code == 200
assert 'access_token' in response.json()
Test login fails with wrong password.
FastAPI
response = client.post('/login', data={'username': 'alice', 'password': 'wrong'})
assert response.status_code == 401
Test access to a protected route with a valid token.
FastAPI
response = client.get('/protected-route', headers={'Authorization': 'Bearer validtoken'})
assert response.status_code == 200
Test access denied without token.
FastAPI
response = client.get('/protected-route')
assert response.status_code == 401
Sample Program

This FastAPI app has a simple login endpoint and a protected route. The test client checks login success, failure, and access control.

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.testclient import TestClient

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

fake_users_db = {
    "johndoe": {
        "username": "johndoe",
        "password": "secret"
    }
}

def fake_verify_token(token: str):
    if token == "validtoken":
        return True
    return False

@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = fake_users_db.get(form_data.username)
    if not user or user["password"] != form_data.password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password"
        )
    return {"access_token": "validtoken", "token_type": "bearer"}

@app.get("/protected-route")
async def protected_route(token: str = Depends(oauth2_scheme)):
    if not fake_verify_token(token):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials"
        )
    return {"message": "You are authenticated"}

client = TestClient(app)

def test_authentication():
    # Test successful login
    response = client.post("/token", data={"username": "johndoe", "password": "secret"})
    assert response.status_code == 200
    assert "access_token" in response.json()

    # Test failed login
    response = client.post("/token", data={"username": "johndoe", "password": "wrong"})
    assert response.status_code == 401

    # Test access protected route with valid token
    response = client.get("/protected-route", headers={"Authorization": "Bearer validtoken"})
    assert response.status_code == 200
    assert response.json() == {"message": "You are authenticated"}

    # Test access protected route without token
    response = client.get("/protected-route")
    assert response.status_code == 401

# Run tests
if __name__ == "__main__":
    test_authentication()
    print("All authentication tests passed.")
OutputSuccess
Important Notes

Always test both success and failure cases for authentication.

Use TestClient to simulate real HTTP requests in tests.

Keep test data simple and clear to understand what is being tested.

Summary

Testing authentication ensures your app only lets in the right users.

Use FastAPI's TestClient to simulate login and protected route access.

Check both successful and failed login attempts to cover all cases.