Skip to content

Commit

Permalink
Test for security schemes
Browse files Browse the repository at this point in the history
  • Loading branch information
caspervdw committed May 17, 2024
1 parent b226eab commit 16be657
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
3 changes: 3 additions & 0 deletions clean_python/fastapi/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ def get_router(
# 'scope' is implemented using FastAPI's dependency injection system
route_options.setdefault("dependencies", [])
if not public:
assert (
len(auth_dependencies) > 0
), "when not using auth, explicitly specify public=True on each endpoint"
route_options["dependencies"].extend(auth_dependencies)
if scope is not None:
assert not public
Expand Down
4 changes: 2 additions & 2 deletions clean_python/fastapi/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class OAuth2Schema(OAuth2AuthorizationCodeBearer):

def __init__(self, settings: OAuth2Settings):
super().__init__(
scheme_name="OAuth2Bearer",
scheme_name="OAuth2",
authorizationUrl=str(settings.authorization_url),
tokenUrl=str(settings.token_url),
scopes=settings.scopes,
Expand All @@ -75,7 +75,7 @@ class JWTBearerTokenSchema(HTTPBearer):
"""

def __init__(self):
super().__init__(scheme_name="OAuth2Bearer", bearerFormat="JWT")
super().__init__(scheme_name="Bearer", bearerFormat="JWT")

async def __call__(self) -> None:
pass
26 changes: 23 additions & 3 deletions tests/oauth2/test_service_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,31 @@ def test_public_ok(app, client: TestClient, jwk_patched):
assert not jwk_patched.called


def test_auth_schema(app, client: TestClient):
def test_auth_security_schemes(app, client: TestClient):
response = client.get("v1/openapi.json")

assert response.status_code == HTTPStatus.OK
schema = response.json()

assert schema["components"]["securitySchemes"] == {}
assert schema["paths"]["/foo"]["get"]["security"] == {}
schemes = schema["components"]["securitySchemes"]

assert len(schemes) == 1

# don't know how to get the version of the parametrized fixture here
if list(schemes)[0] == "Bearer":
assert schemes["Bearer"] == {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
}
elif list(schemes[0]) == "OAuth2":
assert schemes["OAuth2"] == {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://server/token",
"scopes": {},
"tokenUrl": "https://server/token",
}
},
}

0 comments on commit 16be657

Please sign in to comment.