2
votes

I'm using the Serverless framework to create an API. Endpoints are defined in the serverless.yml file, creating API Gateway endpoints that route through a custom Authorizer function and resolve to Go Lambda functions.

However, if a client hits an endpoint that has not been explicitly defined, passing in their JWT Token in the Authorization header, API Gateway returns a 403 Forbidden response with the following body:

{
  "message": "'{{JWT TOKEN}}' not a valid key=value pair (missing equal-sign) in Authorization header: 'Bearer {{JWT TOKEN}}'"
}

The 403 Forbidden status seems appropriate, but I'd like to send an easier to understand error message back to my clients in the body of the response.

Is there a way to modify the response body when an invalid endpoint is requested?

1

1 Answers

2
votes

Unfortunately, the Serverless Framework does not support customizing API Gateway default responses natively (yet). There is an existing issue in the repository, if you are interested in following it.

For now, you will have to use CloudFormation to achieve this. There are a number of options you can use to customize error responses. You will want to know specifically what ResponseType you want to change.

For your use case, it looks like the MISSING_AUTHENTICATION_TOKEN Response Type is what you are looking for. This is an example you can adapt and add to your serverless.yml (via the resources section):

resources:
  Resources:
    MissingAuthenticationTokenGatewayResponse: # Custom name, you can change it
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseType: MISSING_AUTHENTICATION_TOKEN # The Response Type to customize
        RestApiId:
          Ref: 'ApiGatewayRestApi'
        StatusCode: '403' # The returned HTTP code
        ResponseParameters:
          # Set CORS
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseTemplates:
          application/json: |
            {
              "error": "$context.authorizer.customErrorMessage"
            }

In ResponseTemplates, you can set the JSON output as you see fit. This example simply set an error property, which will contain the value of the property customErrorMessage of the Lambda authorizer output context property. You can learn more about this here. You can also set it to be a static string if you want to, but being able to dynamically change the error message in your code is rather nice.