AWS API Gateway配置问题:同时处理无效URL与请求验证错误
I've run into this exact quirk with API Gateway before—when no route matches, it can unexpectedly attempt to parse your Authorization header even if you haven't attached an authorizer to that (non-existent) route, leading to those confusing token format errors instead of a proper 404. Here's how to fix it without needing a {proxy+} catch-all or extra Lambdas:
Root Cause
API Gateway has a default behavior where, if a request includes an Authorization header and no route matches, it still tries to validate the header format against its default expected schema (which assumes key=value pairs, not the Bearer <token> format). This triggers the INVALID_AUTHORIZATION_TOKEN error instead of returning a 404. If there's no Authorization header, it triggers MISSING_AUTHENTICATION_TOKEN instead.
Fix: Targeted Gateway Response Mappings
Instead of using DEFAULT_4XX (which overrides all 4xx responses, including your BAD_REQUEST_BODY), you can map the specific error codes that get triggered for invalid endpoints to return 404, while keeping your existing validation error mapping intact.
Update your OpenAPI spec's x-amazon-apigateway-gateway-responses section with these entries:
x-amazon-apigateway-gateway-responses: # Keep your existing request validation error response BAD_REQUEST_BODY: statusCode: 400 responseTemplates: application/json: | {"message": "Invalid request body: $context.error.validationErrorString"} # Handle invalid endpoints with a Bearer Token in the header INVALID_AUTHORIZATION_TOKEN: statusCode: 404 responseTemplates: application/json: | {"message": "Not found"} # Handle invalid endpoints with no Authorization header MISSING_AUTHENTICATION_TOKEN: statusCode: 404 responseTemplates: application/json: | {"message": "Not found"}
How This Works
BAD_REQUEST_BODY: This only triggers when a valid route is matched, but the request body fails validation. Since it's a specific error type, it won't be overridden by the other mappings.INVALID_AUTHORIZATION_TOKEN: Catches requests to invalid endpoints that include aBearer <token>header (API Gateway misparses this as an invalid key-value pair, triggering this error code). We remap it to return a 404.MISSING_AUTHENTICATION_TOKEN: Catches requests to invalid endpoints with noAuthorizationheader, returning a proper 404 instead of a 403.
Additional Checks
Make sure you haven't enabled any API-level authentication (like API keys or Cognito user pools) in your API Gateway settings. If you have, API Gateway will enforce authentication for all requests—even those to non-existent routes—before checking route matches, which would interfere with this setup. Since you mentioned your authorizer is only attached to valid endpoints, this should already be the case.
Test Scenarios to Verify
- Call
GET /baz(invalid endpoint) with a Bearer Token: Should return404 Not Foundwith your custom message. - Call
GET /bazwithout an Authorization header: Should also return404 Not Found. - Call
POST /barwith a missing required body property: Should return your original400validation error with thevalidationErrorString. - Call valid endpoints like
GET /foo: Should continue to work as expected with your authorizer and validation.
内容的提问来源于stack exchange,提问作者JHH

