Я пытаюсь развернуть API в API Gateway с использованием облачной информации.Методы требуют, чтобы CORS был включен, я следовал шаблону здесь Включите CORS для шлюза API в шаблоне Cloudformation , чтобы сделать это.Вот мой шаблон
AuthorizerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "sts:AssumeRole"
Effect: "Allow"
Principal:
Service:
- "apigateway.amazonaws.com"
Policies:
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "lambda:invokeFunction"
Effect: "Allow"
Resource:
- !GetAtt "MyAPIAuthorizer.Arn"
PolicyName: "lambda"
Authorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
AuthorizerResultTtlInSeconds: 0
AuthorizerCredentials: !GetAtt "AuthorizerRole.Arn"
AuthorizerUri:
Fn::Join:
- ""
-
- "arn:aws:apigateway:"
- Ref: "AWS::Region"
- ":lambda:path/2015-03-31/functions/"
- Fn::GetAtt:
- "MyAPIAuthorizer"
- "Arn"
- "/invocations"
Type: "TOKEN"
IdentitySource: "method.request.header.token"
Name: "DefaultAuthorizer"
RestApiId: !Ref RestApi
MyAPIAuthorizer:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: my-My-lambda-us-east-1
S3Key: node_lambdas.zip
Handler: My-APIAuthorizer.handler
Role: !Ref Role
Runtime: nodejs6.10
Timeout: 300
VpcConfig:
SecurityGroupIds:
- !Ref SecurityGroup
SubnetIds: !Ref Subnets
MyAuthenticateUser:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: My-My-lambda-us-east-1
S3Key: node_lambdas.zip
Handler: My-AuthenticateUser.handler
Role: !Ref Role
Runtime: nodejs6.10
Timeout: 300
VpcConfig:
SecurityGroupIds:
- !Ref SecurityGroup
SubnetIds: !Ref Subnets
#Policies: AWSLambdaDynamoDBExecutionRole
MyAuthenticateUserApiGatewayInvoke:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt "MyAuthenticateUser.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${RestApi}/*/*/*"
MyAuthenticateUserResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref RestApi
ParentId: !Ref ApiResourceParent
PathPart: authenticateuser
MyAuthenticateUserPost:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref RestApi
ResourceId: !Ref MyAuthenticateUserResource
HttpMethod: POST
AuthorizationType: NONE
Integration:
IntegrationHttpMethod: POST
Type: AWS
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !GetAtt "MyAuthenticateUser.Arn"
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
MyAuthenticateUserOptions:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref RestApi
ResourceId: !Ref MyAuthenticateUserResource
HttpMethod: OPTIONS
AuthorizationType: NONE
Integration:
IntegrationHttpMethod: POST
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
Type: MOCK
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: true
method.response.header.Access-Control-Allow-Methods: true
method.response.header.Access-Control-Allow-Origin: true
MyFunction:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: My-My-lambda-us-east-1
S3Key: node_lambdas.zip
Handler: My-Function.handler
Role: !Ref Role
Runtime: nodejs6.10
Timeout: 300
VpcConfig:
SecurityGroupIds:
- !Ref SecurityGroup
SubnetIds: !Ref Subnets
#Policies: AWSLambdaDynamoDBExecutionRole
MyFunctionApiGatewayInvoke:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt "MyFunction.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${RestApi}/*/*/*"
MyFunctionResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref RestApi
ParentId: !Ref ApiResourceParent
PathPart: Function
MyFunctionGet:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref RestApi
ResourceId: !Ref MyFunctionResource
HttpMethod: GET
AuthorizationType: CUSTOM
AuthorizerId: !Ref Authorizer
Integration:
IntegrationHttpMethod: GET
Type: AWS
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !GetAtt "MyFunction.Arn"
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
MyFunctionOptions:
Type: AWS::ApiGateway::Method
Properties:
RestApiId: !Ref RestApi
ResourceId: !Ref MyFunctionResource
HttpMethod: OPTIONS
AuthorizationType: NONE
Integration:
IntegrationHttpMethod: GET
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
Type: MOCK
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: true
method.response.header.Access-Control-Allow-Methods: true
method.response.header.Access-Control-Allow-Origin: true
После развертывания API метод MyAuthenticateUserPost
возвращает 200 со следующими заголовками ответа
Access-Control-Allow-Origin → *
Соединение → keep-alive
Длина содержимого → 249
Тип содержимого → application / json
Дата → Пт, 28 сентября 2018 21:15:38 GMT
Через → 1.1 sdlkfnsdlk.cloudfront.net (CloudFront)
X-Amz-Cf-Id → dflknsdlfkn
X-Amzn-Trace-Id → Root =sdlkfnsdlk; Sampled = 0
X-Cache → Мисс от облачного фронта
x-amz-apigw-id → sdklfnsdlk
x-amzn-RequestId → slkfnlsdk
, но метод MyFunctionGet
возвращает 500 со следующими заголовками ответа
Соединение → keep-alive
Content-Length → 36
Тип контента → application / json
Дата → Пт, 28 сентября 2018 21:19:04 GMT
Через → 1.1 slkdfnk.cloudfront.net (CloudFront)
X-Amz-Cf-Id → dsklfnsdlk
X-Cache → Ошибка в облачном фронте
x-amz-apigw-id → dlsfknsdlkfn
x-amzn-RequestId → sdkfnsdkln
В ответе 500 отсутствуют заголовки Access-Control-Allow-Origin
и X-Amzn-Trace-Id
.Разница между этими двумя методами заключается в том, что рабочий метод является POST и не имеет авторизации, а тот, который не работает, является GET и имеет собственный Authorizer.Я могу заставить метод возвращать 500 работ, если я зайду в консоль API Gateway, выберу метод GET-> Запрос на интеграцию и сохраню функцию Lambda следующим образом:
ТоФункция уже присутствует в этом поле после развертывания облачной информации, и я добавил разрешение в шаблон, но метод API Gateway не будет работать, если я не выполню этот шаг вручную.У меня есть около 50 методов, поэтому я хотел бы полностью автоматизировать это.Я что-то упустил в своем шаблоне?
Обновление: В ответ на @jny я обновил ответы интеграции в моем методе Get, например,
IntegrationResponses:
- StatusCode: 200
SelectionPattern: "2\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 300
SelectionPattern: "3\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 400
SelectionPattern: "4\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 500
SelectionPattern: "5\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
- StatusCode: 300
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
- StatusCode: 400
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
- StatusCode: 500
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: true
Я также сделалто же самое обновление для моего метода параметров
IntegrationResponses:
- StatusCode: 200
SelectionPattern: "2\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 300
SelectionPattern: "3\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 400
SelectionPattern: "4\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
- StatusCode: 500
SelectionPattern: "5\\{d}2"
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,token'"
method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
method.response.header.Access-Control-Allow-Origin: "'*'"
MethodResponses:
- StatusCode: 200
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
- StatusCode: 300
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
- StatusCode: 400
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
- StatusCode: 500
ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
Я все еще вижу ответ 500 при вызове метода API