API 使用 Cognito 联合身份进行网关身份验证

API Gateway authentication with Cognito Federated Identities

我想使用 Cognito 联合实体(允许通过 Google 等登录),以允许访问 Web javascript 应用程序的 API 网关。 我设法通过使用 Google 登录获得了 Cognito 的 sessionToken,但我被困在启用会话令牌的 API 网关配置上。

整个联合实体身份验证工作流程是否有好的教程?

谢谢!

由于您想通过经过身份验证的 Cognito 身份调用 APIs,首先

  1. 修改身份池的身份验证角色,让 api 执行策略,您可以将托管策略 "AmazonAPIGatewayInvokeFullAccess" 附加到相应的角色
  2. 在API网关中各自方法请求下,添加Authorization as "AWS_IAM"
  3. 使用"IAM" auth时需要对请求进行签名,这里有说明https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html

  4. 您可以从 API 网关的舞台面板生成并下载 SDK,然后通过 sdk 调用 api,而不是 #3。

获得 Cognito 会话后,您可以使用如下所示的 sdk 进行调用

var apigClient = apigClientFactory.newClient({
    accessKey: AWSCognito.config.credentials.accessKeyId,
    secretKey: AWSCognito.config.credentials.secretAccessKey,
    sessionToken: AWSCognito.config.credentials.sessionToken
});

var params = {
    // This is where any modeled request parameters should be added.
    // The key is the parameter name, as it is defined in the API in API Gateway.
};

var body = {};

var additionalParams = {
    // If there are any unmodeled query parameters or headers that must be
    //   sent with the request, add them here.
    headers: {
        'Content-Type': 'application/json'
    },
    queryParams: {}
};

apigClient.<resource><Method>(params, body, additionalParams)
.then(function(result) {
    // 
}).catch(function(err) {
    //
});