Skip to content

Commit 5243dd7

Browse files
committed
fix: add example and moved oauth2 config
1 parent b07c4f9 commit 5243dd7

File tree

4 files changed

+97
-12
lines changed

4 files changed

+97
-12
lines changed

aws_lambda_powertools/event_handler/openapi/swagger_ui/__init__.py

-2
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
)
44
from aws_lambda_powertools.event_handler.openapi.swagger_ui.oauth2 import (
55
OAuth2Config,
6-
OAuth2UnsafeConfig,
76
generate_oauth2_redirect_html,
87
)
98

109
__all__ = [
1110
"generate_swagger_html",
1211
"generate_oauth2_redirect_html",
1312
"OAuth2Config",
14-
"OAuth2UnsafeConfig",
1513
]

aws_lambda_powertools/event_handler/openapi/swagger_ui/oauth2.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
# ruff: noqa: E501
22
from typing import Dict, Optional, Sequence
33

4-
from pydantic import BaseModel, Field
4+
from pydantic import BaseModel, Field, validator
55

66
from aws_lambda_powertools.event_handler.openapi.pydantic_loader import PYDANTIC_V2
7+
from aws_lambda_powertools.shared.functions import powertools_dev_is_set
78

89

910
# Based on https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/
@@ -15,6 +16,10 @@ class OAuth2Config(BaseModel):
1516
# The client ID for the OAuth2 application
1617
clientId: str = Field(alias="client_id")
1718

19+
# The client secret for the OAuth2 application. This is sensitive information and requires the explicit presence
20+
# of the POWERTOOLS_DEV environment variable.
21+
clientSecret: Optional[str] = Field(alias="client_secret", default=None)
22+
1823
# The realm in which the OAuth2 application is registered. Optional.
1924
realm: Optional[str] = Field(default=None)
2025

@@ -44,15 +49,14 @@ class Config:
4449
extra = "allow"
4550
allow_population_by_field_name = True
4651

47-
48-
class OAuth2UnsafeConfig(OAuth2Config):
49-
"""
50-
This class extends the OAuth2Config class and includes the client secret.
51-
This class NEVER BE USED IN PRODUCTION as it will expose sensitive information.
52-
"""
53-
54-
# The client secret for the OAuth2 application. This is sensitive information.
55-
clientSecret: str = Field(alias="client_secret")
52+
@validator("clientSecret", always=True)
53+
def client_secret_only_on_dev(cls, v: Optional[str]) -> Optional[str]:
54+
if v and not powertools_dev_is_set():
55+
raise ValueError(
56+
"cannot use client_secret without POWERTOOLS_DEV mode. See "
57+
"https://docs.powertools.aws.dev/lambda/python/latest/#optimizing-for-non-production-environments",
58+
)
59+
return v
5660

5761

5862
def generate_oauth2_redirect_html() -> str:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
AWSTemplateFormatVersion: "2010-09-09"
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for Oauth2 Cognito User Pool + Swagger UI
4+
5+
Globals:
6+
Function:
7+
Timeout: 5
8+
Runtime: python3.12
9+
Tracing: Active
10+
Environment:
11+
Variables:
12+
LOG_LEVEL: INFO
13+
POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1
14+
POWERTOOLS_LOGGER_LOG_EVENT: true
15+
POWERTOOLS_SERVICE_NAME: example
16+
17+
Resources:
18+
HelloWorldFunction:
19+
Type: AWS::Serverless::Function
20+
Properties:
21+
CodeUri: hello_world/
22+
Handler: swagger_ui_oauth2.lambda_handler
23+
Events:
24+
AnyApiEvent:
25+
Type: Api
26+
Properties:
27+
Path: /{proxy+} # Send requests on any path to the lambda function
28+
Method: ANY # Send requests using any http method to the lambda function
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from aws_lambda_powertools import Logger, Tracer
2+
from aws_lambda_powertools.event_handler import (
3+
APIGatewayRestResolver,
4+
Response,
5+
)
6+
from aws_lambda_powertools.event_handler.openapi.models import (
7+
OAuth2,
8+
OAuthFlowAuthorizationCode,
9+
OAuthFlows,
10+
)
11+
from aws_lambda_powertools.event_handler.openapi.swagger_ui import OAuth2Config
12+
13+
tracer = Tracer()
14+
logger = Logger()
15+
16+
oauth2 = OAuth2Config(
17+
client_id="your_oauth2_client_id",
18+
client_secret="your_oauth2_secret",
19+
app_name="OAuth2 Test",
20+
)
21+
22+
app = APIGatewayRestResolver(enable_validation=True)
23+
24+
# NOTE: for this to work, your OAuth2 redirect url needs to precisely follow this format:
25+
# https://<your_api_id>.execute-api.<region>.amazonaws.com/<stage>/swagger?format=oauth2-redirect
26+
app.enable_swagger(
27+
oauth2_config=oauth2,
28+
security_schemes={
29+
"oauth": OAuth2(
30+
flows=OAuthFlows(
31+
authorizationCode=OAuthFlowAuthorizationCode(
32+
authorizationUrl="https://your-cognito-domain.eu-central-1.amazoncognito.com/oauth2/authorize",
33+
tokenUrl="https://your-cognito-domain.eu-central-1.amazoncognito.com/oauth2/token",
34+
),
35+
),
36+
),
37+
},
38+
security=[{"oauth": []}],
39+
)
40+
41+
42+
@app.get("/")
43+
def helloworld() -> Response[dict]:
44+
logger.info("Hello, World!")
45+
return Response(
46+
status_code=200,
47+
body={"message": "Hello, World"},
48+
content_type="application/json",
49+
)
50+
51+
52+
@logger.inject_lambda_context(log_event=True)
53+
@tracer.capture_lambda_handler
54+
def lambda_handler(event, context):
55+
return app.resolve(event, context)

0 commit comments

Comments
 (0)