Cognito 错误 AccessDenied 使用从 Cognito 身份池获取的凭证(Javascript AWS SDK,区域 cn-north-1)

Cognito error AccessDenied with credentials obtained from cognito identity pool (Javascript AWS SDK, region cn-north-1)

我已经尝试让 Cognito 工作一天多了。

我想开始工作的场景是 this page (https://docs.amazonaws.cn/en_us/cognito/latest/developerguide/cognito-scenarios.html)

上的 "Authenticate with a Third Party and Access AWS Services with an Identity Pool"

目前我使用 AWS.EnvironmentCredentials 生成凭据,创建一个新的 CognitoIdentity 并使用它在我们的后端调用 getOpenIdTokenForDeveloperIdentity

AWS.config.credentials = new AWS.EnvironmentCredentials(...);
AWS.config.update({region: 'cn-north-1'});
const cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});

const params = {
  IdentityPoolId: 'cn-north-1:XXXXXX',
  Logins: {
    '<DeveloperProviderName>': identifierStr,
  },
};

这很好用,我可以将 return 需要的 tokenidentityId 接收到我的前端。我在那里交换 tokenidentityId 以获取凭据。

AWS.config.region = 'cn-north-1';
const cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});
const params = {
  IdentityId: identityId,
  Logins: {
    'cognito-identity.cn-north-1.amazonaws.com.cn': token, //using the key for cn-north-1
  }
};

cognitoidentity.getCredentialsForIdentity(params, (err, data) => {
  if (err){
    //handle error
  } else { 
    //get credentials
    //using AccessKeyId and SecretKey and SessionToken to use AWS services
  }
});

这里会报错InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.

为什么会出现此错误?我该如何解决?

我在想我可能需要更改后端的凭据配置,正如身份池中的示例代码所建议的那样,但这会在服务器上产生错误 Missing credentials in config

// Initialize the Amazon Cognito credentials provider
AWS.config.region = 'cn-north-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'cn-north-1:XXXXXXX',
});

edit:经过一些研究,我在配置中添加了 SessionToken(除了 AccessKey 和 SecretKey),但现在出现了一个新错误 AccessDenied。不过,我检查了我的角色配置,并为我经过身份验证的角色分配了正确的权限。

我也找到了第二个错误的答案。

我缺少正确的存储桶策略(因为我正在尝试访问 S3)。存储桶策略需要更新

{
    "Version": "2012-10-17",
    "Id": "Policy01",
    "Statement": [
        {
            "Sid": "Statement01",
            "Effect": "Allow",
            "Principal": {
                "AWS": <IdentityPoolAuthenticatedRole>
            },
            "Action": [
                "s3:DeleteObject",
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws-cn:s3:::<bucketName>/*" // <* or specified keyName>
        },
        ...
        // more statements
    ]
}

据我所知,存储桶知道来自的请求没问题。


blog post 帮助我走上了正确的轨道,但它假设您正在为未经授权的用户设置并且不使用身份池。