我已经向API网关中的API端点添加了授权。
这为事件添加了identity
属性,
identity:
{
cognitoIdentityPoolId: null,
accountId: null,
cognitoIdentityId: null,
caller: null,
sourceIp: 'detracted',
accessKey: null,
cognitoAuthenticationType: null,
cognitoAuthenticationProvider: null,
userArn: null,
userAgent: 'Amazon CloudFront',
user: null },
apiId: 'detracted' },
body: null,
isBase64Encoded: false
}
但是那里主要是null
。那么如何访问呼叫者的Cognito用户名?
编辑:
我添加了一个映射模板。但是,这是一个GET请求,因此我不知道它是否有作用,因为工具提示会说明数据已附加到主体上。
## 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($allParams = $input.params())
{
"body-json" : $input.json('$'),
"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
},
"context" : {
"account-id" : "$context.identity.accountId",
"api-id" : "$context.apiId",
"api-key" : "$context.identity.apiKey",
"authorizer-principal-id" : "$context.authorizer.principalId",
"caller" : "$context.identity.caller",
"cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
"cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
"cognito-identity-id" : "$context.identity.cognitoIdentityId",
"cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
"http-method" : "$context.httpMethod",
"stage" : "$context.stage",
"source-ip" : "$context.identity.sourceIp",
"user" : "$context.identity.user",
"user-agent" : "$context.identity.userAgent",
"user-arn" : "$context.identity.userArn",
"request-id" : "$context.requestId",
"resource-id" : "$context.resourceId",
"resource-path" : "$context.resourcePath",
"username" : "$context.authorizer.claims['cognito:username']"
}
}
"event" : {
"username" : "$context.authorizer.claims['cognito:username']"
}
答案 0 :(得分:1)
您要通过调用API Gateway发送用户的idToken,对吧?
我认为您已经在此解决方案中成功获取了用户的Cognito信息。
在对API Gateway的调用中,您包括带有令牌的Authorization标头,如下所示:
var url = YOURURL;
var options = {
method: "GET",
headers: {
'Authorization': COGNITOUSER_IDTOKEN
}
}
fetch(url, options);
有很多方法可以获取用户的ID令牌,因此我在这里不作规定。
只要这样做,就可以通过集成请求(API网关中API阶段中的)映射模板访问令牌中的信息。
在映射模板中,您可以使用以下代码:
{
"username" : "$context.authorizer.claims['cognito:username']"
}
然后,您可以在Lambda函数中通过引用“ event.username”来访问它。