'AWS API Gateway with Lambda Authorizer returns 500 instead of 401

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 Authorization header (API key) is valid, everything works as expected.
  • When the Authorization header is missing, a 401 response is returned, as expected. In this scenario, API GW doesn't even call the authorizer.
  • When an invalid Authorization header is provided, the lambda throws a RuntimeException("Unauthorized"). I would expect API GW to return a 401 error, but instead a 500 Internal Server error 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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source