1
from base64 import b64encode
3
from fastapi import FastAPI, Security
4
from fastapi.security import HTTPBasic, HTTPBasicCredentials
5
from fastapi.testclient import TestClient
9
security = HTTPBasic(realm="simple", description="HTTPBasic scheme")
13
def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
14
return {"username": credentials.username, "password": credentials.password}
17
client = TestClient(app)
20
def test_security_http_basic():
21
response = client.get("/users/me", auth=("john", "secret"))
22
assert response.status_code == 200, response.text
23
assert response.json() == {"username": "john", "password": "secret"}
26
def test_security_http_basic_no_credentials():
27
response = client.get("/users/me")
28
assert response.json() == {"detail": "Not authenticated"}
29
assert response.status_code == 401, response.text
30
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
33
def test_security_http_basic_invalid_credentials():
34
response = client.get(
35
"/users/me", headers={"Authorization": "Basic notabase64token"}
37
assert response.status_code == 401, response.text
38
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
39
assert response.json() == {"detail": "Invalid authentication credentials"}
42
def test_security_http_basic_non_basic_credentials():
43
payload = b64encode(b"johnsecret").decode("ascii")
44
auth_header = f"Basic {payload}"
45
response = client.get("/users/me", headers={"Authorization": auth_header})
46
assert response.status_code == 401, response.text
47
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
48
assert response.json() == {"detail": "Invalid authentication credentials"}
51
def test_openapi_schema():
52
response = client.get("/openapi.json")
53
assert response.status_code == 200, response.text
54
assert response.json() == {
56
"info": {"title": "FastAPI", "version": "0.1.0"},
62
"description": "Successful Response",
63
"content": {"application/json": {"schema": {}}},
66
"summary": "Read Current User",
67
"operationId": "read_current_user_users_me_get",
68
"security": [{"HTTPBasic": []}],
77
"description": "HTTPBasic scheme",