![](/img/trans.png)
[英]How to directly invoke a Chalice Lambda from another Lambda without going through the API Gateway and Authorizer again?
[英]Get context data from Lambda Authorizer (APi Gateway)
我正在使用 Aws Lambda 授權方來保護 Api 網關。 授權 lambda 函數是使用來自 aws 的藍圖 ( https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/python/api-gateway-authorizer-python ) 用 python 編寫的。 py )
我在“藍圖”中添加了這段代碼
if(event['authorizationToken'] == 'allow'):
policy.allowAllMethods()
else:
policy.denyAllMethods()
# Finally, build the policy
authResponse = policy.build()
# new! -- add additional key-value pairs associated with the authenticated principal
# these are made available by APIGW like so: $context.authorizer.<key>
# additional context is cached
context = {
'key': 'somevalue, # $context.authorizer.key -> value
'number' : 1,
'bool' : True
}
# context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it
# context['obj'] = {'foo':'bar'} <- also invalid
authResponse['context'] = context
return authResponse
但是,在附加到路由的 lambda 函數中,我無法從授權方找到上下文值。 如何從 context[key] 獲取值?
解決方案是在集成請求上使用映射模板。 如果您查看路由管道,您會看到在到達 Lambda 函數之前,您有一個“集成請求”部分(以及一個集成響應)
在集成請求中,您可以選擇通過映射模板將輸入編輯為 lambda 函數。
所以,我創建了一個新的映射模板(使用“Where”沒有定義模板)內容 - 類型使用 application/json 並在實際模板中使用類似 #set($inputRoot = $input.path('$'))
{
"key":"$context.authorizer.key"
}
注意:上述模板將刪除原始輸出。 該數據位於 $inputRoot 中,您可以使用此格式將其添加到響應中
{
"key":"$context.authorizer.key",
"originalkey":$inputRoot.originalkey
}
在接受的答案的幫助下,我想出了這個:
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($inputRoot = $input.path('$'))
#set($authorizer = $context.authorizer)
#set($allParams = $input.params())
{
#foreach($key in $inputRoot.keySet())
"$key" : "$util.escapeJavaScript($inputRoot.get($key))"
#if($foreach.hasNext),#end
#end,
"context" : {
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
#if($foreach.hasNext),#end
#end
},
#foreach($key in $context.keySet())
"$key" : "$util.escapeJavaScript($context.get($key))"
#if($foreach.hasNext),#end
#end,
"authorizer": {
#foreach($key in $authorizer.keySet())
"$key" : "$util.escapeJavaScript($authorizer.get($key))"
#if($foreach.hasNext),#end
#end
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.