在Ruby中为无服务器框架编写授权程序

在Ruby中为无服务器框架编写授权程序,ruby,lambda,serverless-framework,Ruby,Lambda,Serverless Framework,我正试图使用无服务器框架编写一个授权程序来保护对lambda的调用。我用的是Ruby 配置: provider: name: aws runtime: ruby2.5 iamRoleStatements: - Effect: Allow Action: - KMS:Decrypt Resource: ${self:custom.kmsSecrets.keyArn} functions: authorize: handler:

我正试图使用无服务器框架编写一个授权程序来保护对lambda的调用。我用的是Ruby

配置:

provider:
  name: aws
  runtime: ruby2.5

  iamRoleStatements:
    - Effect: Allow
      Action:
      - KMS:Decrypt
      Resource: ${self:custom.kmsSecrets.keyArn}

functions:
  authorize:
    handler: handler.authorize
  hello:
    handler: handler.protected
    events:
      - http:
          path: protected
          method: get
          authorizer: authorize
授权人:

def authorize(event:, context:)
  if is_authorized?
    {
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "execute-api:Invoke",
            "Resource": [ context.invoked_function_arn ],
            "Effect": "Allow"
          }
        ]
      },
      "principalId": "seeker"
    }.to_json
  end
end
我想实现的身份验证是基于令牌的:
是否已授权?
方法将接收令牌,然后返回允许访问
受保护的
lambda函数的策略。
我不完全确定
PrincipalId
参数中的内容-我没有
user.id


现在它抱怨说:
seeker-dev-authorize没有被授权执行:iam:CreatePolicy-on-resource:policy-seeker-allowed
,这让我很困惑:我无法创建策略。。。关于政策?我应该在哪里设置此权限?在
IAM
serverless.yml
上?因为我已经在serverless中设置了对密钥进行编码/解码的权限,也许我也应该这样做?

我以前没有使用过自定义授权程序,但我组织了一个小的hello world项目来尝试,这就是我发现的

受保护功能和授权人功能:

def authorize(event:, context:)
  {
    "principalId": "test",
    "policyDocument": {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Action": "execute-api:Invoke",
          "Effect": "Allow",
          "Resource": event["methodArn"]
        }
      ]
    }
  }
end

def hello(event:, context:)
  { statusCode: 200, body: JSON.generate('This is a protected endpoint!') }
end
请注意,我返回的是散列,而不是带有
的字符串to_json
,在使用
to_json
时,授权人返回了一个错误

还请注意,我使用
事件[“methodArn”]
获取受保护的lambda ARN,使用
上下文。调用的函数\u ARN
也会导致我出错

此外,如果请求中不包含授权标头,将返回“未经授权的错误”:

最后,关于
principalId

principalId是授权人响应的必需属性。它表示调用方的主要标识符。这可能因应用程序而异,但可能是用户名、电子邮件地址或唯一ID

资料来源:

curl -X GET https://endpoint/dev/hello -H 'Authorization: test'