diff --git a/docs/core/event_handler/api_gateway.md b/docs/core/event_handler/api_gateway.md index 39554c21e40..1f9618839f9 100644 --- a/docs/core/event_handler/api_gateway.md +++ b/docs/core/event_handler/api_gateway.md @@ -1103,6 +1103,14 @@ Security schemes are declared at the top-level first. You can reference them glo 1. Using the oauth security scheme defined bellow, scoped to the "admin" role. +=== "Global security schemes and optional security per route" + + ```python title="security_schemes_global_and_optional.py" hl_lines="22 37-46" + --8<-- "examples/event_handler_rest/src/security_schemes_global_and_optional.py" + ``` + + 1. To make security optional in a specific route, an empty security requirement ({}) can be included in the array. + OpenAPI 3 lets you describe APIs protected using the following security schemes: | Security Scheme | Type | Description | diff --git a/examples/event_handler_rest/src/security_schemes_global_and_optional.py b/examples/event_handler_rest/src/security_schemes_global_and_optional.py new file mode 100644 index 00000000000..2a890efd5e4 --- /dev/null +++ b/examples/event_handler_rest/src/security_schemes_global_and_optional.py @@ -0,0 +1,48 @@ +from aws_lambda_powertools import Logger, Tracer +from aws_lambda_powertools.event_handler import ( + APIGatewayRestResolver, +) +from aws_lambda_powertools.event_handler.openapi.models import ( + OAuth2, + OAuthFlowAuthorizationCode, + OAuthFlows, +) + +tracer = Tracer() +logger = Logger() + +app = APIGatewayRestResolver(enable_validation=True) + + +@app.get("/protected", security=[{"oauth": ["admin"]}]) +def protected() -> dict: + return {"hello": "world"} + + +@app.get("/unprotected", security=[{}]) # (1)! +def unprotected() -> dict: + return {"hello": "world"} + + +@logger.inject_lambda_context +@tracer.capture_lambda_handler +def lambda_handler(event, context): + return app.resolve(event, context) + + +if __name__ == "__main__": + print( + app.get_openapi_json_schema( + title="My API", + security_schemes={ + "oauth": OAuth2( + flows=OAuthFlows( + authorizationCode=OAuthFlowAuthorizationCode( + authorizationUrl="https://xxx.amazoncognito.com/oauth2/authorize", + tokenUrl="https://xxx.amazoncognito.com/oauth2/token", + ), + ), + ), + }, + ), + )