Skip to content

Commit d76607c

Browse files
feat(event_sources): add get_context() to standardize API Gateway Lambda Authorizer context in v1 and v2 (aws-powertools#3454)
Co-authored-by: Heitor Lessa <[email protected]>
1 parent 05dd82b commit d76607c

File tree

4 files changed

+79
-5
lines changed

4 files changed

+79
-5
lines changed

aws_lambda_powertools/utilities/data_classes/api_gateway_proxy_event.py

+38
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,25 @@ def integration_latency(self) -> Optional[int]:
3333
"""The authorizer latency in ms."""
3434
return self.get("integrationLatency")
3535

36+
def get_context(self) -> Dict[str, Any]:
37+
"""Retrieve the authorization context details injected by a Lambda Authorizer.
38+
39+
Example
40+
--------
41+
42+
```python
43+
ctx: dict = request_context.authorizer.get_context()
44+
45+
tenant_id = ctx.get("tenant_id")
46+
```
47+
48+
Returns:
49+
--------
50+
Dict[str, Any]
51+
A dictionary containing Lambda authorization context details.
52+
"""
53+
return self._data
54+
3655

3756
class APIGatewayEventRequestContext(BaseRequestContext):
3857
@property
@@ -184,6 +203,25 @@ def get_lambda(self) -> Optional[Dict[str, Any]]:
184203
"""Lambda authorization context details"""
185204
return self.get("lambda")
186205

206+
def get_context(self) -> Dict[str, Any]:
207+
"""Retrieve the authorization context details injected by a Lambda Authorizer.
208+
209+
Example
210+
--------
211+
212+
```python
213+
ctx: dict = request_context.authorizer.get_context()
214+
215+
tenant_id = ctx.get("tenant_id")
216+
```
217+
218+
Returns:
219+
--------
220+
Dict[str, Any]
221+
A dictionary containing Lambda authorization context details.
222+
"""
223+
return self.get("lambda", {}) or {}
224+
187225
@property
188226
def iam(self) -> Optional[RequestContextV2AuthorizerIam]:
189227
"""IAM authorization details used for making the request."""

tests/events/apiGatewayProxyV2LambdaAuthorizerEvent.json

+12-3
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,19 @@
2424
"stage": "$default",
2525
"requestId": "id",
2626
"authorizer": {
27+
"jwt": {
28+
"claims": {
29+
"claim1": "value1"
30+
},
31+
"scopes": [
32+
"scope1",
33+
"scope2"
34+
]
35+
},
2736
"lambda": {
28-
"key": "value"
37+
"tenantId": "123-456-789-012"
2938
}
30-
},
39+
},
3140
"apiId": "api-id",
3241
"domainName": "id.execute-api.us-east-1.amazonaws.com",
3342
"domainPrefix": "id",
@@ -47,4 +56,4 @@
4756
},
4857
"body": "{\r\n\t\"a\": 1\r\n}",
4958
"isBase64Encoded": false
50-
}
59+
}

tests/unit/data_classes/test_api_gateway_proxy_event.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,10 @@ def test_api_gateway_proxy_event_with_principal_id():
150150
assert authorizer.integration_latency == raw_event["requestContext"]["authorizer"]["integrationLatency"]
151151
assert authorizer.get("integrationStatus", "failed") == "failed"
152152

153+
# Accessing context with direct function
154+
context_variables = request_context.authorizer.get_context()
155+
assert context_variables.get("user_id") == raw_event["requestContext"]["authorizer"]["user_id"]
156+
153157

154158
def test_api_gateway_proxy_v2_event():
155159
raw_event = load_event("apiGatewayProxyV2Event.json")
@@ -200,9 +204,23 @@ def test_api_gateway_proxy_v2_lambda_authorizer_event():
200204

201205
request_context = parsed_event.request_context
202206
assert request_context is not None
207+
203208
lambda_props = request_context.authorizer.get_lambda
204209
assert lambda_props is not None
205-
assert lambda_props.get("key") == "value"
210+
assert lambda_props.get("tenantId") == raw_event["requestContext"]["authorizer"]["lambda"]["tenantId"]
211+
212+
# Accessing context with direct function
213+
context_variables = request_context.authorizer.get_context()
214+
assert context_variables.get("tenantId") == raw_event["requestContext"]["authorizer"]["lambda"]["tenantId"]
215+
216+
jwt_claims = request_context.authorizer.jwt_claim
217+
assert jwt_claims is not None
218+
assert jwt_claims.get("claim1") == raw_event["requestContext"]["authorizer"]["jwt"]["claims"]["claim1"]
219+
220+
jwt_scopes = request_context.authorizer.jwt_scopes
221+
assert jwt_scopes is not None
222+
assert jwt_scopes[0] == raw_event["requestContext"]["authorizer"]["jwt"]["scopes"][0]
223+
assert jwt_scopes[1] == raw_event["requestContext"]["authorizer"]["jwt"]["scopes"][1]
206224

207225

208226
def test_api_gateway_proxy_v2_iam_event():

tests/unit/parser/test_apigwv2.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,16 @@ def test_api_gateway_proxy_v2_event_lambda_authorizer():
7979

8080
lambda_props: RequestContextV2Authorizer = request_context.authorizer.lambda_value
8181
assert lambda_props is not None
82-
assert lambda_props["key"] == raw_event["requestContext"]["authorizer"]["lambda"]["key"]
82+
assert lambda_props["tenantId"] == raw_event["requestContext"]["authorizer"]["lambda"]["tenantId"]
83+
84+
jwt_claims: RequestContextV2Authorizer = request_context.authorizer.jwt.claims
85+
assert jwt_claims is not None
86+
assert jwt_claims["claim1"] == raw_event["requestContext"]["authorizer"]["jwt"]["claims"]["claim1"]
87+
88+
jwt_scopes: RequestContextV2Authorizer = request_context.authorizer.jwt.scopes
89+
assert jwt_scopes is not None
90+
assert jwt_scopes[0] == raw_event["requestContext"]["authorizer"]["jwt"]["scopes"][0]
91+
assert jwt_scopes[1] == raw_event["requestContext"]["authorizer"]["jwt"]["scopes"][1]
8392

8493

8594
def test_api_gateway_proxy_v2_event_iam_authorizer():

0 commit comments

Comments
 (0)