首页 > 解决方案 > 获取我在 Lambda 函数中访问 Cognito 身份?缺少部分拼图的完整示例

问题描述

我已经阅读了一些 AWS 文档和许多关于在 Lambda 函数中访问 Cognito Identity 的问题,这是我迄今为止最好的尝试。但它不起作用。告诉我可能缺少什么!

客户

我从客户端调用 Lambda 函数

fetch('api/public/libraries/sign-out-discourse', {
    method: 'GET',
    headers: new Headers([
        ['Accept', 'application/json'],
        ['Content-Type', 'application/json'],
        // I get the idToken from CognitoUser.getSession => getIdToken(). It is possible to get a jwtToken without decoded payload with getIdToken().getJwtToken(). I think it is the idToken and not the jwtToken I should send to the API Gateway, but I am not sure.
        ['Authorization', idToken],
    ]),
})

API 网关

资源方法

GET

设置

Auth: AWS_IAM
Integration type: Lambda Function
// I don't know if Execution role is relevant
Execution role: arn:aws:iam::*:user/*
Invoke with caller credentials: true
// I don't know if Credentials cache is relevant
Credentials cache: Add caller's principal to the cache key

映射模板

我不知道我在这里做什么我不知道这个模板是否对没有从客户端发送正文的 GET 请求执行任何操作。

设置

Request body passthrough: When there are no templates defined (recommended)
Content-Type: application/json

模板代码

// The template is based on the default template. The only thing I have added is username to event and context.

#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']"
}

授权人

我添加了一个授权人:

Name: Something something
Type: Cognito
Cognito user pool: Choose the user pool from the drop down
Token Source: Authorization
Token Validation: //blank

Lambda 函数

运行时是节点 6。

'use strict';

const util = require('util');

exports.handler = (event, context, callback) => {
    console.log(util.inspect(event, {
        showHidden: false,
        depth: null
    }));
    console.log(util.inspect(context, {
        showHidden: false,
        depth: null
    }));
    console.log(util.inspect(callback, {
        showHidden: false,
        depth: null
    }));
}

控制台日志

用户名不是事件的属性,也不是上下文的属性。

事件对象具有令人失望的身份属性。

identity: 
{
    cognitoIdentityPoolId: null,
    accountId: null,
    cognitoIdentityId: null,
    caller: null,
    sourceIp: 'redacted',
    accessKey: null,
    cognitoAuthenticationType: null,
    cognitoAuthenticationProvider: null,
    userArn: null,
    userAgent: 'Amazon CloudFront',
    user: null },
    apiId: 'redacted' },
    body: null,
    isBase64Encoded: false 
}

标签: amazon-web-servicesaws-lambdaaws-api-gateway

解决方案


如果您在 lambda 的集成请求中选择了使用 Lambda 代理集成,则所有令牌的声明都将在 event.requestContext.authorizer.claims 上传递。

从这里得到答案:get-cognito-user-pool-identity-in-lambda-function


推荐阅读