目前,我有一个基于用户是否经过正确身份验证的服务器 HTML 的 AWS ApiGateway + Lambda 架构。我正在尝试实现这个 Cognito 和自定义 Lambda 授权器。我希望我的 Lambda 始终返回 HTML,并根据传递的 cookie,为登录/注销状态生成 HTML。在我看来,最好有一个单独的授权者来执行令牌验证并将标头传递给生成 HTML 的 Lambda。
怎么能做到这一点?
我正在使用 AWS Sam 模板来定义我的 CF 堆栈。查看我当前的模板:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: A Lambda function for rendering HTML pages with authentication
Resources:
WebAppGenerator:
Type: 'AWS::Serverless::Function'
Properties:
Handler: app.handler
Runtime: nodejs12.x
CodeUri: .
Description: A Lambda that generates HTML pages dynamically
MemorySize: 128
Timeout: 20
Events:
ProxyRoute:
Type: Api
Properties:
RestApiId: !Ref WebAppApi
Path: /{proxy+}
Method: GET
WebAppApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: WebTokenAuthorizer
Authorizers:
WebTokenAuthorizer:
FunctionArn: !GetAtt WebAppTokenAuthorizer.Arn
WebAppTokenAuthorizer:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: authorizer.handler
Runtime: nodejs12.x
在我的授权人(Typescript)中,我正在考虑生成一个始终具有“允许”效果的策略。但是,如果缺少授权令牌(尚未基于 cookie),则它已经返回 403。请参阅:
function generatePolicy(principalId: string, isAuthorized: boolean, resource): APIGatewayAuthorizerResult {
const result: APIGatewayAuthorizerResult = {
principalId,
policyDocument: {
Version: '2012-10-17',
Statement: []
}
};
if (resource) {
result.policyDocument.Statement[0] = {
Action: 'execute-api:Invoke',
Effect: 'Allow',
Resource: resource
};
}
result.context = {
isAuthorized
};
return result
}