I'm building an AWS Lambda Request Authorizer for API Gateway. The stack uses Serverless Framework and the Lambda is in Java.
- When the provided
Authorizationheader (API key) is valid, everything works as expected. - When the
Authorizationheader is missing, a 401 response is returned, as expected. In this scenario, API GW doesn't even call the authorizer. - When an invalid
Authorizationheader is provided, the lambda throws aRuntimeException("Unauthorized"). I would expect API GW to return a 401 error, but instead a500 Internal Servererror is received. Not good.
Here's the lambda request handler code:
@Override
public AuthPolicy handleRequest(AuthorizerEvent authorizerEvent, Context context) {
try {
return getPolicy(authorizerEvent);
} catch (Exception exception) {
throw new RuntimeException("Unauthorized");
}
}
CloudWatch confirms the RuntimeException is thrown:
<last message logged by authorizer>
Unauthorized: java.lang.RuntimeException
java.lang.RuntimeException: Unauthorized
at com.example.serverless.AuthorizerHandler.handleRequest(AuthorizerHandler.java:30)
at com.example.serverless.AuthorizerHandler.handleRequest(AuthorizerHandler.java:20)
Here's the log when testing the authorizer in the AWS Console, which indicates the error condition was not handled correctly or at all:
> Authorizer result body before parsing: {}
> Execution failed due to configuration error: Could not parse policy due to null response or empty JSON.
> AuthorizerConfigurationException
What am I doing wrong or not doing right?