Home > Enterprise >  How to return 401 response in AWS API Gateway Lambda Authorizer?
How to return 401 response in AWS API Gateway Lambda Authorizer?

Time:04-24

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?

CodePudding user response:

The answer is squirrelled away in a comment in a sample repo:

"""you can send a 401 Unauthorized response to the client by failing like so:"""
"""raise Exception('Unauthorized')"""

You just need to raise a plain exception with exactly the string 'Unauthorized'. Then the API Gateway will reject the connection with a nice 401 Unauthorized.

  • Related