Skip to content

Commit 5813363

Browse files
docs(auth): add middleware testing example
1 parent 65a57da commit 5813363

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

‎docs/utilities/auth.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ Use `reason.value` for log fields and metric dimensions. Do not parse exception
189189

190190
## Testing your code
191191

192-
Use `mock_claims` to replace `verifier.verify()` while testing route behavior without cryptography or network calls. Wrap the call to `app.resolve()` in `mock_claims(verifier, claims)` and include an Authorization header so the middleware still exercises credential extraction.
192+
Use `mock_claims` to test the complete middleware Lambda without cryptography or network calls:
193193

194-
`mock_claims` restores the verifier when the context manager exits and returns an independent copy of the supplied claims. It bypasses signature and claim validation, so keep separate verification tests for the token profiles your application accepts.
194+
```python title="test_middleware.py"
195+
--8<-- "examples/auth_alpha/jwt/tests/test_middleware.py"
196+
```
197+
198+
The test still sends an HTTP API event, extracts the Bearer token, and checks the required scope before invoking the route. `mock_claims` replaces only token verification and restores the verifier when the context manager exits. Keep separate verification tests for the token profiles your application accepts.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import json
2+
3+
from aws_lambda_powertools.utilities.auth_alpha.jwt.testing import mock_claims
4+
5+
6+
def test_list_orders(monkeypatch):
7+
monkeypatch.setenv("ISSUER_URL", "https://idp.example.com/")
8+
monkeypatch.setenv("RESOURCE_URL", "https://api.example.com")
9+
10+
from middleware import lambda_handler, verifier
11+
12+
event = {
13+
"version": "2.0",
14+
"routeKey": "GET /orders",
15+
"rawPath": "/orders",
16+
"rawQueryString": "",
17+
"headers": {"authorization": "Bearer test-token"},
18+
"requestContext": {
19+
"http": {"method": "GET", "path": "/orders"},
20+
"stage": "$default",
21+
},
22+
"isBase64Encoded": False,
23+
}
24+
claims = {"sub": "test-user", "scope": "orders:read"}
25+
26+
with mock_claims(verifier, claims):
27+
response = lambda_handler(event, {})
28+
29+
assert response["statusCode"] == 200
30+
assert json.loads(response["body"]) == {"subject": "test-user", "orders": []}

0 commit comments

Comments
 (0)