集成 API 网关与 lambda 授权者,但在调用它以允许策略时,它返回内部服务器错误,否认其正常工作

问题描述 投票:0回答:1

这是我正在使用的模板:https://github.com/devashish234073/cloud-experiments/blob/main/aws/cloudformations/lambda_api_gw_authorizer/lambda_api_gw_authorizer.yaml

当我从邮递员调用 api 网关端点并在授权标头中使用值“allow”时,我收到“内部服务器错误”

但是对于“否认”我得到了正确的回应:

对于 lambda 授权者,我使用来自 https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html

的代码

从模板中,这是 lambda 授权者部分:

AuthorizerForAPIGW:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: "authorizer-for-api-gw"
      Role: !GetAtt LambdaFuncRoleForAuthorizer.Arn
      Handler: src/index.handler
      Runtime: nodejs16.x
      MemorySize: 320
      Timeout: 20
      InlineCode: |
        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
          }
        };
        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;
            console.log("statement",statementOne);
            console.log("policyDocument",policyDocument);
          }
          authResponse.context = {
            "stringKey": "stringval",
            "numberKey": 123,
            "booleanKey": true
          };
          return authResponse;
        }
amazon-web-services aws-cloudformation gateway lambda-authorizer
1个回答
0
投票

貌似api gateway下的cloudformation模板这一段有问题,我评论了一下:

而是在 lambda 定义中添加了以下内容来修复它:

现在拒绝授权仍然像以前一样工作,并且允许我从 lambda 得到响应:

© www.soinside.com 2019 - 2024. All rights reserved.