我正在尝试编写一个授权方来保护使用无服务器框架对 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
我想要实现的身份验证是基于 token 的:is_authorized?
方法将接收 token ,然后返回一个允许访问protected
lambda 的策略功能。
我不完全确定 PrincipalId
参数中的内容 - 我没有 user.id
。
现在它提示:seeker-dev-authorize 无权执行:iam:CreatePolicy on resources:policy seer-allowed
这让我很困惑:我无法创建策略……关于政策?我应该在哪里设置这个权限?在 IAM
或 serverless.yml
上?因为我已经设置了在无服务器中对 key 进行编码/解码的权限,所以也许我应该对此执行相同的操作?
最佳答案
我以前没有使用过自定义授权者,但我整理了一个小型的 hello world 项目来尝试一下,这就是我发现的。
protected 函数和授权函数:
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
时,我收到了授权者返回的错误。
另请注意,我使用 event["methodArn"]
来获取 protected lambda ARN,使用 context.invoked_function_arn
也导致了错误。
除此之外,如果请求中不包含授权 header ,将返回“未经授权的错误”:
curl -X GET https://endpoint/dev/hello -H 'Authorization: test'
最后,关于principalId
:
The principalId is a required property on your authorizer response. It represents the principal identifier for the caller. This may vary from application-to-application, but it could be a username, an email address, or a unique ID.
来源:https://www.alexdebrie.com/posts/lambda-custom-authorizers/
关于ruby - 使用 Ruby 为无服务器框架编写授权者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55654880/