我正在研究一些无服务器应用程序,并希望使用AWS SAM进行所有部署。我没有找到很多关于如何为我的端点包含自定义授权器的信息。有一些(一年前)的帖子谈论在Swagger(我没有使用)或Cloudformation中定义它们。
有没有人有这些方法的例子,或者知道如何在SAM模板中定义自定义授权者?
答案 0 :(得分:5)
更新:AWS无服务器应用程序模型(SAM)现在支持将API Auth Object
定义为AWS::Serverless::Api
资源的一部分:
Auth:
MyLambdaTokenAuth:
FunctionPayloadType: TOKEN
FunctionArn: !GetAtt MyAuthFunction.Arn
Identity:
Header: Authorization
ReauthorizeEvery: 300
原始答案:
我最终在我的模板中使用AWS swagger扩展功能。我在GitHub上有一个基本的例子:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An example serverless "Hello World" application with a custom authorizer.
Resources:
ApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
DefinitionBody:
swagger: 2.0
info:
title:
Ref: AWS::StackName
securityDefinitions:
test-authorizer:
type: apiKey
name: Authorization
in: header
x-amazon-apigateway-authtype: custom
x-amazon-apigateway-authorizer:
type: token
authorizerUri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${TestAuthorizerFunc.Arn}/invocations
authorizerResultTtlInSeconds: 5
paths:
"/":
get:
x-amazon-apigateway-integration:
httpMethod: post
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorld.Arn}/invocations
responses: {}
security:
- test-authorizer: []
HelloWorld:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.6
CodeUri: ./HelloWorld
Events:
GetApi:
Type: Api
Properties:
Path: /
Method: get
RestApiId:
Ref: ApiGateway
TestAuthorizerFunc:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.6
CodeUri: ./TestAuthorizerFunc
TestAuthorizerFuncPerm:
Type: AWS::Lambda::Permission
DependsOn:
- ApiGateway
- TestAuthorizerFunc
Properties:
Action: lambda:InvokeFunction
FunctionName:
Ref: TestAuthorizerFunc
Principal: apigateway.amazonaws.com
在API网关资源中,swagger定义的YAML添加在DefinitionBody
项下。自定义授权程序定义为:
securityDefinitions:
test-authorizer:
type: apiKey
name: Authorization
in: header
x-amazon-apigateway-authtype: custom
x-amazon-apigateway-authorizer:
type: token
authorizerUri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${TestAuthorizerFunc.Arn}/invocations
authorizerResultTtlInSeconds: 5
然后,授权者将附加到它将保护的路径的定义中:
paths:
"/":
get:
x-amazon-apigateway-integration:
httpMethod: post
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorld.Arn}/invocations
responses: {}
security:
- test-authorizer: []
Lambda函数的代码可以在这里找到:
https://github.com/brysontyrrell/Serverless-Hello-World/tree/master/hello-world
答案 1 :(得分:0)
根据此处的讨论,SAM似乎不支持授权程序 https://github.com/awslabs/serverless-application-model/issues/49
引用开发者:
@WilixLead授权程序尚未在SAM中本机支持。 #248是所有APIGW功能的父跟踪问题。
由于SAM的这种限制,我今天也遇到了障碍。我正在回归传统的云形成方法。