Is it possible to throw custom error message from API Gateway Lambda Authorizer

0

I have created an Lambda Authorizer for custom authorization in API Gateway. I need to throw custom error message like this.

{ errorCode: 'xyz_12#', errorType: 'Constraint error', errorMessage: 'Need permission to perform this action', statusCode: 401 }

Is it possible from lambda authorizer?

1 Antwort
1

Yes. At the end of the example authorizer in the docs (https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html), there is way to output optional data. Updating with your values, it would be something like this:

    // Optional output with custom properties of the String, Number or Boolean type.
    authResponse.context = {
        "errorCode": "xyz_12#",
        "errorType": "Constraint error",
        "errorMessage": "Need permisssion to perform this action"
    };

In the body mapping template, you'd access these as follows:

{"errorCode":"$context.authorizer.context.errorCode", "errorType": "$context.authorizer.context.errorCode"}

The one caveat here is that you can't specify the HTTP error code. The authorizer has to generate a 'Deny' policy which then results in an HTTP 403.

More discussion is available here: https://stackoverflow.com/questions/47921803

profile pictureAWS
Corey
beantwortet vor 2 Jahren
    1. I have tried evrything and nothing works for me. I want to customize the error mesage in the lambda authorizer if the token is expired or malformed. Followed this post as well https://stackoverflow.com/questions/47921803 . This is the main problem

    2. Another wierd problem i am facing is that the callback with custom errors also does not work in simple lambda calls. I am really tired of this. can someone please guide how to resolve. It gives me InvokeError. secondary

    callback("unauthorized"); // not working return callback(new Error("JSON.stringify(myErrorObj)")); // not working

  • This seems to only apply for the API Gateway V1 (REST) not for the V2 (HTTP) API Gateway. I really need something like this for the V2 API Gateway and a custom authorizer

  • Should the mapping template be the following?

    {"errorCode":"$context.authorizer.errorCode", "errorType": "$context.authorizer.errorType"}
    

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen