How to throw custom error message from API Gateway custom authorizer

api gateway always returns 200
aws lambda return status code
aws lambda error handling node
api gateway error codes
aws api gateway
aws api gateway tutorial
api gateway authorizer return
api gateway request authorizer

Here in the blue print says, API gateway will respond with 401: Unauthorized.

I wrote the same raise Exception('Unauthorized') in my lambda and was able to test it from Lambda Console. But in POSTMAN, I'm receiving status 500 with body:

{
  message: null`
} 

I want to add custom error messages such as "Invalid signature", "TokenExpired", etc., Any documentation or guidance would be appreciated.

This is totally possible but the docs are so bad and confusing.

Here's how you do it:

There is an object called $context.authorizer that you have access to in your gateway responses template. You can read more about it here: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

Here is an examample of populating this authorizer object from your authorizer lambda like so:

// A simple TOKEN authorizer example to demonstrate how to use an authorization token 
// to allow or deny a request. In this example, the caller named 'user' is allowed to invoke 
// a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke 
// the request if the token value is 'deny'. If the token value is 'Unauthorized', the function 
// returns the 'Unauthorized' error with an HTTP status code of 401. For any other token value, 
// the authorizer returns an 'Invalid token' error. 

exports.handler =  function(event, context, callback) {
    var token = event.authorizationToken;
    switch (token.toLowerCase()) {
        case 'allow':
            callback(null, generatePolicy('user', 'Allow', event.methodArn));
            break;
        case 'deny':
            
            callback(null, generatePolicy('user', 'Deny', event.methodArn));
            break;
        case 'unauthorized':
            callback("Unauthorized");   // Return a 401 Unauthorized response
            break;
        default:
            callback("Error: Invalid token"); 
    }
};

       var generatePolicy = function(principalId, effect, resource) {
            var authResponse = {};
            
            authResponse.principalId = principalId;
            if (effect && resource) {
                var policyDocument = {};
                policyDocument.Version = '2012-10-17'; 
                policyDocument.Statement = [];
                var statementOne = {};
                statementOne.Action = 'execute-api:Invoke'; 
                statementOne.Effect = effect;
                statementOne.Resource = resource;
                policyDocument.Statement[0] = statementOne;
                authResponse.policyDocument = policyDocument;
            }
            
            // Optional output with custom properties of the String, Number or Boolean type.
            authResponse.context = {
                "stringKey": "stringval custom anything can go here",
                "numberKey": 123,
                "booleanKey": true,
            };
            return authResponse;
        }

API Gateway Custom Authorizer: Control error message and code , In case it helps someone: CA = custom authorizer. error code: AWS doesn't fully allow a CA implementation to dictate the error code sent back  Under Settings, click the pencil icon to the right Authorization and choose the jwt-rsa-custom-authorizer custom authorizer you created in part 3. Click the check mark icon to save your choice of custom authorizer. Make sure the API Key Required field is set to false.

i use @maxwell solutions, using custom Resource ResponseTemplates. for deny response show like in bellow.

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

you can check this, https://github.com/SeptiyanAndika/serverless-custom-authorizer

Handle Lambda errors in API Gateway, Configure a Lambda authorizer using the console · Input to a Lambda For Lambda custom integrations, you must map errors returned by Lambda in the standard Lambda error, containing Malformed input as the error message: Otherwise, API Gateway throws an invalid configuration error response at runtime​. Note. API Gateway Configuration. Create a new API Gateway and add a GET method to the root resource. Bind the method to the Lambda you just created and give it the Lambda basic execution role. Method Response Navigate to the Method Response for GET and add a 400 Status response. This makes 400 available to assign a regex to in Integration Response.

This can be easily achieved by using the context.fail() function.

Example:

const customAuthorizer: Handler = (event, context: Context, callback: Callback) => {        
    authenticate(event)
        .then((res) => {
            // result should be as described in AWS docs
            callback(null, res);
        })
        .catch((err) => {
            context.fail("Unauthorized");
        });
}

This will return a 401 response with following body.

{
    "message": "Unauthorized"
}

This can also be achieved by throwing an error:

throw new Error('Unauthorized');

Custom Authorizer, how to return 401, Custom Authorizer, how to return 401 http status code http://docs.aws.amazon.​com/apigateway/latest/developerguide/use-custom-authorizer.html error if the validation fails, irrespective of the Exception message thrown. "aws apigateway test-invoke-authorizer --rest-api-id --authorizer-id --headers Authorization='Value'". Any errors will directly show up on the console were you are running the command. rest-api-key: The key of the API Gateway where your authorizer is created. authorizer-id: The ID of the authorizer you want to test.

I'm not sure what is causing the 500 message: null response. Possibly misconfiguration of the Lambda function permissions.

To customize the Unauthorized error response, you'll set up a Gateway Response for the UNAUTHORIZED error type. You can configure response headers and payload here.

Custom Lambda Authorizer returning blank error message , { “message”: null } How can i add a more custom error message. Custom Lambda Authorizer returning blank error message If I throw an error like throw new Error("blabla") from the lambda-authorizer, why the response is  API Gateway calls the custom authorizer (which is a Lambda function) with the authorization token. If the authorization token is valid, the custom authorizer returns the appropriate AWS Identity and Access Management (IAM) policies. API Gateway uses the policies returned in step 3 to authorize the request.

How to throw custom error message from API Gateway - html, How to throw custom error message from API Gateway custom authorizer - aws-​api-gateway. As you can see, we are overriding a base method out of the ResponseEntityExceptionHandler and providing our own custom implementation. That's not always going to be the case – sometimes we're going to need to handle a custom exception that doesn't have a default implementation in the base class, as we'll get to see later on here. Next:

How to return a custom error object and status code from API , Why does it have to be so hard?API Gateway and Lambda are great until you need to return an error object from your REST API. It's a maze of  Configure the Lambda function as an API Gateway authorizer and configure an API method to require it, as described in Configure a Lambda authorizer using the API Gateway console. Alternatively, if you need a cross-account Lambda authorizer, see Configure a cross-account Lambda authorizer .

The Complete Guide to Custom Authorizers with AWS Lambda and , API Gateway custom authorizers are a great way to separate auth logic Background on custom authorizers and their benefits and downsides; Basic you can throw an error in your Lambda function to stop the request from  API Gateway allows you to define a Lambda Authorizer to execute custom authentication and authorization logic before allowing a client access to the actual API route they have requested. A Lambda Authorizer function is somewhat similar to a middleware in Express.js in that it gets called before the main route handler function, it can reject a request outright, or if it allows the request to proceed, it can enhance the request event with extra data that the main route handler can then

Comments
  • You should keep in mind that Gateway Responses are only applied after you re-deploy your API. You can also utilize Response Headers instead of editing the default Body Mapping Template to keep global 403 errors to return correct error message body.
  • Even if that works, looks pretty hacky. According to AWS docs, the purpose of that context object is: "In addition to returning an IAM policy, the Lambda authorizer function must also return the caller's principal identifier. It can also optionally return a context object containing additional information that can be passed into the integration backend. For more information, see Output from an Amazon API Gateway Lambda Authorizer." Source: docs.aws.amazon.com/apigateway/latest/developerguide/…
  • If I throw an error from inside the authorizer like throw new Error("blabla"), why the error message is not {message: "blabla"}? Without such behavior we can't send custom error messages with 500 status codes.
  • Thanks for the repo, this is really useful for anyone trying to figure this out using the serverless framework.
  • This will allow you to deny a request, but there is no mention of a custom error response message, as request in the original question