API网关GET失败,出现 "缺少认证令牌"(但POST正常)。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了API网关GET失败,出现 "缺少认证令牌"(但POST正常)。相关的知识,希望对你有一定的参考价值。
我有一个工作的Lambda + API网关 "hello world "的组合,如下所示------。
lambda.py
import boto3, json, logging
logger=logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger('botocore').setLevel(logging.WARNING)
def api_gateway(fn):
def wrapped(event, context):
body=json.loads(event["body"])
resp=fn(body, context)
return {"statusCode": 200,
"headers": {"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"},
"body": json.dumps(resp)}
return wrapped
@api_gateway
def handler(event, context):
logging.info("event: %s" % event)
return {"hello": "world"}
api_gateway.yaml
---
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
FunctionName:
Type: String
StageName:
Type: String
FunctionArn:
Type: String
HttpMethod:
Type: String
Default: POST
Outputs:
GatewayURL:
Value: !Sub "https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${StageName}"
Resources:
ApiGateway:
Properties:
Name: !Sub "${FunctionName}-${StageName}"
Type: AWS::ApiGateway::RestApi
ApiGatewayMethod:
Properties:
AuthorizationType: NONE
HttpMethod: !Ref HttpMethod
Integration:
IntegrationHttpMethod: POST
Type: AWS_PROXY
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !Ref FunctionArn
ResourceId: !GetAtt ApiGateway.RootResourceId
RestApiId: !Ref ApiGateway
Type: AWS::ApiGateway::Method
ApiGatewayDeployment:
Properties:
RestApiId: !Ref ApiGateway
StageName: !Ref StageName
DependsOn:
- ApiGatewayMethod
Type: AWS::ApiGateway::Deployment
ApiGatewayPermission:
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref FunctionArn
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGateway}/*/${HttpMethod}/"
Type: AWS::Lambda::Permission
这对一个人来说很好。POST
要求-
curl -X POST -H "Content-Type: application/json" https://XXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev -d "{"foo": "bar"}"
{"hello": "world"}
但我需要一个 GET
:
我希望这是一个简单的改变,只是改变网关 HttpMethod
参数为 GET
- 部署得很好,但是当我尝试ping它时------。
curl -X GET https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev
{"message":"Missing Authentication Token"}
在 Lambda 日志中没有显示任何错误,所以这看起来像是 API Gateway 层面的某种故障 :(
有什么办法可以调整API网关的配置,使GET请求工作?
答案
原来你需要定义一个 额外 API网关资源来实现这一工作 -
Resources:
ApiGatewayStage:
Type: AWS::ApiGateway::Stage
Properties:
RestApiId: !Ref ApiGateway
DeploymentId: !Ref ApiGatewayDeployment
StageName: !Ref StageName
有了这一点,你应该可以同时进行 GET
和 POST
请求才能工作。
如果没有这个功能,API Gateway似乎会创建某种 "默认 "阶段,一个只支持POST请求的阶段。
以上是关于API网关GET失败,出现 "缺少认证令牌"(但POST正常)。的主要内容,如果未能解决你的问题,请参考以下文章
安装 Composer 失败并出现“缺少 openssl 扩展”错误