Skip to content

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

Merged
leandrodamascena merged 2 commits into
developfrom
openapi/improve-doc-security
Jan 22, 2025
Merged

leandrodamascena merged 2 commits into
developfrom
openapi/improve-doc-security

Conversation

@leandrodamascena

Copy link
Copy Markdown
Contributor

Issue number: #5893

Summary

Changes

The OpenAPI v3 specification defines an optional security mechanism with {}, so this means that if you add a security scheme on a specific route like this @app.get("/unprotected", security=[{}]) it will make the authorization optional in that specific route.

Reference: spec.openapis.org/oas/v3.1.0.html#fixed-fields

A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement ({}) can be included in the array.

User experience

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"]}])  # (1)!
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",
                        ),
                    ),
                ),
            },
        ),
    )

Checklist

If your change doesn't seem to apply, please leave them unchecked.

Is this a breaking change?

RFC issue number:

Checklist:

  • Migration process documented
  • Implement warnings (if it can live side by side)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@leandrodamascena
leandrodamascena requested a review from a team January 22, 2025 10:18
@pull-request-size pull-request-size Bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Jan 22, 2025
@boring-cyborg boring-cyborg Bot added the documentation Improvements or additions to documentation label Jan 22, 2025
@codecov

codecov Bot commented Jan 22, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.20%. Comparing base (b74a659) to head (2961d7c).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5895   +/-   ##
========================================
  Coverage    96.20%   96.20%           
========================================
  Files          232      232           
  Lines        10956    10956           
  Branches      2027     2027           
========================================
  Hits         10540    10540           
  Misses         327      327           
  Partials        89       89           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment thread docs/core/event_handler/api_gateway.md Resolved
Comment thread docs/core/event_handler/api_gateway.md Resolved
@leandrodamascena

Copy link
Copy Markdown
Contributor Author

Hey @anafalcao! Thanks a lot for the review! Can you please check again?

@sonarqubecloud

Copy link
Copy Markdown

@anafalcao anafalcao left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVED! Thank you Leo

@leandrodamascena
leandrodamascena merged commit bb24814 into develop Jan 22, 2025
@leandrodamascena
leandrodamascena deleted the openapi/improve-doc-security branch January 22, 2025 11:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Global apigateway swagger security config not overwritten by specific route configs with empty security

2 participants