如何调用API网关授权者背后的lambda

时间:2019-03-19 11:05:23

标签: node.js amazon-web-services aws-lambda authorization

我有以下CloudFormation堆栈。 2个lambda(问候和Auth),其中API Gateway配置为使用Auth lambda进行授权。

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
  GreetingsApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyAuthorizer
        Authorizers:
          MyAuthorizer:
            FunctionArn: !GetAtt AuthLambda.Arn

  GreetingsLambda:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: "s3://<bucket-name>/code.zip"
      Handler: src/index.greeting
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref GreetingsApiGateway
            Path: /hello
            Method: get

  AuthLambda:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: "s3://<bucket-name>/code.zip"
      Handler: src/index.auth

Globals:
  Function:
    Runtime: nodejs8.10
  # check whether I can use resources within globals

Outputs:
  ApiURL:
    Description: "OUR API URL"
    Value: !Sub "https://${GreetingsApiGateway}.execute-api.${AWS::Region}.amazonaws.com/Prod/"

我的lambda的代码如下:

exports.greeting = async () => ({ statusCode: 200, body: "Hello Beautiful World!" });

exports.auth = async () => ({ statusCode: 200, body: "I wanna do the authorisation!" });

我希望授权会一直失败,而且希望在CloudWatch日志中查看来自Auth lambda的日志。

正在发生的事情:

从API网关内部调用

如果我在API网关控制台中没有任何标题的情况下进行测试,则会得到“ Hello Beautiful World”结果。我的CloudWatch模板中没有lambda身份验证日志。

从POSTMAN调用

我尝试在GET请求的标头中发送此输入。响应是“未授权”,而Auth lambda CloudWatch日志中没有任何日志。

{
    "type":"TOKEN",
    "authorizationToken":"<caller-supplied-token>",
    "methodArn":"arn:aws:execute-api:<regionId>:<accountId>:<apiId>/<stage>/<method>/<resourcePath>"
}

发生了什么事?

1 个答案:

答案 0 :(得分:0)

要检索响应,我们需要使用Authorization标头,但仍然不明白为什么来自API Gateway控制台的请求检索了响应。