Skip to content

Commit

Permalink
docs(event_handler): demonstrate handling optional security routes (#…
Browse files Browse the repository at this point in the history
…5895)

* Adding example on how to work with optional security routes

* Adding example on how to work with optional security routes
  • Loading branch information
leandrodamascena authored Jan 22, 2025
1 parent b74a659 commit bb24814
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
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",
),
),
),
},
),
)

0 comments on commit bb24814

Please sign in to comment.