Skip to content

docs(event_handler): demonstrate handling optional security routes #5895

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/core/event_handler/api_gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
@@ -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",
),
),
),
},
),
)
Loading