【发布时间】:2021-09-17 19:28:42
【问题描述】:
问题描述
我在 SAM 中使用 API Gateway 创建了一个 Lambda 函数,然后部署它,它按预期工作。在 API 网关中,我使用了 HttpApi 而不是 REST API。
然后,我想添加一个带有简单响应的 Lambda 授权方。因此,我遵循了 SAM 和 API Gateway 文档,并提出了以下代码。
当我调用路由 items-list 时,它现在返回 401 Unauthorized,这是预期的。
但是,当我将标题 myappauth 添加到值 "test-token-abc" 时,我得到一个 500 Internal Server Error。
我检查了这个页面,但似乎所有列出的步骤都可以https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-http-lambda-integrations/
我按照以下说明为 API 网关启用了日志记录:https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html
但我得到的只是这样的东西(编辑了我的 IP 和请求 ID):
[MY-IP] - - [07/Jul/2021:08:24:06 +0000] "GET GET /items-list/{userNumber} HTTP/1.1" 500 35 [REQUEST-ID]
(也许我可以配置记录器,使其打印更有意义的错误消息?编辑:我尝试将$context.authorizer.error 添加到日志中,但它不打印任何特定的错误消息,只是打印破折号:-)
我还检查了 Lambda 函数的日志,那里什么都没有(所有日志都来自我添加授权人之前的时间)。 那么,我做错了什么?
我尝试了什么:
这是我使用 sam deploy 部署的 Lambda Authorizer 函数,当我使用带有 myappauth 标头的 event 单独测试它时,它可以工作:
exports.authorizer = async (event) => {
let response = {
"isAuthorized": false,
};
if (event.headers.myappauth === "test-token-abc") {
response = {
"isAuthorized": true,
};
}
return response;
};
这是我使用 sam deploy 部署的 SAM template.yml:
AWSTemplateFormatVersion: 2010-09-09
Description: >-
myapp-v1
Transform:
- AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs14.x
MemorySize: 128
Timeout: 100
Environment:
Variables:
MYAPP_TOKEN: "test-token-abc"
Resources:
MyAppAPi:
Type: AWS::Serverless::HttpApi
Properties:
FailOnWarnings: true
Auth:
Authorizers:
MyAppLambdaAuthorizer:
AuthorizerPayloadFormatVersion: "2.0"
EnableSimpleResponses: true
FunctionArn: !GetAtt authorizerFunction.Arn
FunctionInvokeRole: !GetAtt authorizerFunctionRole.Arn
Identity:
Headers:
- myappauth
DefaultAuthorizer: MyAppLambdaAuthorizer
itemsListFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/v1-handlers.itemsList
Description: A Lambda function that returns a list of items.
Policies:
- AWSLambdaBasicExecutionRole
Events:
Api:
Type: HttpApi
Properties:
Path: /items-list/{userNumber}
Method: get
ApiId: MyAppAPi
authorizerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/v1-handlers.authorizer
Description: A Lambda function that authorizes requests.
Policies:
- AWSLambdaBasicExecutionRole
编辑:
用户 @petey 建议我尝试在我的授权函数中返回一个 IAM 策略,所以我在 template.yml 中将 EnableSimpleResponses 更改为 false,然后我将函数更改如下,但得到了相同的结果:
exports.authorizer = async (event) => {
let response = {
"principalId": "my-user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": event.routeArn
}]
}
};
if (event.headers.myappauth == "test-token-abc") {
response = {
"principalId": "my-user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": event.routeArn
}]
}
};
}
return response;
};
【问题讨论】:
标签: aws-lambda amazon-cloudformation aws-api-gateway aws-sam