我创建了一些Lambda函数,并使用SAM进行了部署。部署成功,但是当尝试到达端点时,我总是会得到
{ message: "Unauthorized" }
即使我正在使用Authentication
标头发送正确的Bearer令牌。然后,如果我去到授权程序并运行测试,则测试顺利通过并在CloudWatch中生成日志,但是当我从前端应用程序或REST客户端应用程序向端点运行请求时,我收到未经授权的消息并检查CloudWatch,不是执行授权者功能。
此外,从Lambda配置中检查Authorizer函数,我可以看到API Gateway Trigger
中存在错误,但不知道这意味着什么。
我使用AWS提供的指南创建了授权者功能:https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html#api-gateway-lambda-authorizer-lambda-function-create
共享我的SAM配置
Resources:
SomeAPI:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
TracingEnabled: true
Auth:
DefaultAuthorizer: MyLambdaTokenAuthorizer
Authorizers:
MyLambdaTokenAuthorizer:
FunctionArn: !GetAtt AuthorizerFunction.Arn
GetActivityStreamFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: get-activity-stream/
Handler: index.handler
Layers:
- !Ref DepencenciesLayer
- !Ref DatabaseLayer
Events:
GetActivityStream:
Type: Api
Properties:
RestApiId: !Ref SomeAPI
Path: /activity-stream
Method: get
## Authorizer Function
AuthorizerFunction:
Type: AWS::Serverless::Function
Properties:
Layers:
- !Ref DepencenciesLayer
CodeUri: authorizer/
Handler: index.handler
关于授权者发送回的响应,它将发送API网关请求的所有参数
{
principalId: decoded.sub,
policyDocument: getPolicyDocument("Allow", params.methodArn),
context: { scope: decoded.scope }
}
我正在使用的运行时是nodejs12.x
,这是一些我从AWS控制台获得的屏幕截图。
经过大量的小时测试,Internet上发现的不同内容之后,当我发现策略文档错误时,我开始有所改进:
之前
const policyDocument = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": effect,
"Action": "execute-api:Invoke",
"Resource": resource
}
]
};
之后
const policyDocument = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": effect,
"Action": [
"execute-api:Invoke"
],
"Resource": [
resource
]
}
]
};
其中Action
和Resource
应该是数组。另外,我将resource
变量设置为'*'
而不是event.methodArn
,因为在缓存授权时,缓存的策略仅与到达的第一个端点匹配,而对其他端点的下一次调用将导致错误:user not authorized for the method requested
。 >
template.yaml
中有其他更改
Resources: SomeAPI: Type: AWS::Serverless::Api Auth: DefaultAuthorizer: MyLambdaTokenAuthorizer AddDefaultAuthorizerToCorsPreflight: false Authorizers: MyLambdaTokenAuthorizer: FunctionArn: !GetAtt AuthorizerFunction.Arn Identity: Header: Authorization ValidationExpression: Bearer.*
AddDefaultAuthorizerToCorsPreflight
值为false
的飞行前调用(OPTIONS
)不会被签名,否则,来自Axios
的所有调用也会失败。