Vikramsinh Gaikwad
Vikramsinh Gaikwad

Reputation: 911

How to customize cognito user pool authorizer's Unauthorized 401 JSON response in AWS API Gateway

I have added Cognito User pool as a Authorizer in AWS API Gateway. Then I have tested this authorizer with id_token and it is working fine. I have used lambda functions for user registration/login with Cognito user pool.

Now my question is how to customize the error response when id_token is expired or when cognito authorizer fails to authenticate current user. Currently I am only getting

{
    "message": "Unauthorized"
}

OR

{
    "message": "The incoming token has expired"
}

with 401 response

Upvotes: 0

Views: 1225

Answers (1)

Suraj Bhatia
Suraj Bhatia

Reputation: 1333

You can make use of Gateway Responses in API Gateway to modify the HTTP status code and response that goes back to a client.

By default, for the scenario you have described, the response is "Unauthorized" and status code is 401. To change this -

  1. Go to "Gateway Responses" on the left column for your API.
  2. Select "Unauthorized" and click on "Edit" on top right.
  3. Click on "application/json: under "Response templates".
  4. Modify the message there as {"message":"Your custom message"} in the "Response body template" section (see screenshot below).
  5. Deploy the API and wait for a minute for changes to propagate.

enter image description here

Upvotes: 1

Related Questions