How to return 401 response in AWS API Gateway Lambda Authorizer?
02:55 22 Apr 2022

I'm using a custom Lambda Authorizer written in Python for an API Gateway Web Socket. How do I return a 401 Unauthorized response from that?

The documentation is fairly vague on it and only has a node.js example:

exports.handler =  function(event, context, callback) {
    var token = event.authorizationToken;
    switch (token) {
        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"); // Return a 500 Invalid token response
    }
};

Alternatively it allows to return an explicit Deny IAM policy:

If the token value is 'deny', the authorizer function returns a 403 Forbidden HTTP response and a Deny IAM policy that looks like the following, and the method request fails:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Deny",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
    }
  ]
}

What if I want to respond with a 401 Unauthorized though? What's the equivalent to callback("Unauthorized") in a Python Lambda handler?

python amazon-web-services aws-lambda aws-api-gateway