Farad
Farad

Reputation: 1065

How to change API Gateway response

I have an aws ApiGateway which verify my token and pass request to lambda.

When I have an error from lambda, APIGateway response is

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "..."
}

But if I don't pass my token, then APIGateway will return me

{
    "message": "Unauthorized"
}

And in postman I have statusCode: 401.

How I want it to be:

{
    "statusCode": 401,
    "error": "Unauthorized"
}

I use serverless.yml to deploy:

functions:
  index:
    handler: dist/index.handler
    events:
    - http:
        cors: true
        path: '/'
        method: any
        authorizer:
          type: COGNITO_USER_POOLS
          authorizerId:
            Ref: ApiGatewayAuthorizer

Please, tell me how I have to change my serverless.yml to change the 'Unauthorized' error to be as at third code example.

Upvotes: 1

Views: 5665

Answers (3)

onicofago
onicofago

Reputation: 302

Adding to @svladimirrc, it will work even if you don't have a custom authorizer in place, just make sure you have the proper name of your API Gateway configured to link to:

resources:
  Resources:
    ApiGatewayRestApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: ${self:provider.stage}-${self:service}
    InvalidApiKeyGatewayResponse:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        RestApiId: 
          Ref: 'ApiGatewayRestApi'
        ResponseType: INVALID_API_KEY
        ResponseTemplates:
          application/json: "{\"success\":false,\"message\":\"Invalid API key\"}"
        StatusCode: '401'

Upvotes: 1

Ali Ince
Ali Ince

Reputation: 9

You can achieve this by modifying Gateway Responses.

  1. Go to API Gateway in AWS Management Console.
  2. Select your API.
  3. Click "Gateway Responses" which can be seen on the left side.
  4. Select "Unauthorized" in the list of Gateway Responses.
  5. Select "application/json" in Response Templates and click "Edit".
  6. Update the response template body based on your requirements.
  7. Click "Save".
  8. Re-deploy your API.

Upvotes: 0

svladimirrc
svladimirrc

Reputation: 234

try to implement this: https://github.com/SeptiyanAndika/serverless-custom-authorizer:

Allows to get reponses like:

{
  "success":false,
  "message":"Custom Deny Message"
}

Upvotes: 2

Related Questions