如何在 AWS API Gateway Lambda 授权方中 return 401 响应?

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

我正在为 API 网关 Web 套接字使用用 Python 编写的自定义 Lambda 授权器。我如何 return 401 Unauthorized 回应?

The documentation 相当含糊,只有一个 node.js 示例:

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
    }
};

或者,它允许 return 明确的拒绝 IAM 策略:

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/"
    }
  ]
}

如果我想用 401 Unauthorized 回复怎么办? Python Lambda 处理程序中的 callback("Unauthorized") 等效于什么?

答案藏在a comment in a sample repo:

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

您只需要使用字符串 'Unauthorized' 引发一个简单的异常。然后 API 网关将拒绝连接并带有 401 Unauthorized.