如何将 CognitoAuth 身份验证对象转换为 AWS-SDK 凭证

How to turn an CognitoAuth auth object into AWS-SDK credentials

我有一个 Cognito 用户池,我可以使用以下代码成功登录到我的应用程序:

const authData = {
        ClientId : '2222222222222', // Your client id here
        AppWebDomain : '1111111111.auth.us-east-1.amazoncognito.com',
        TokenScopesArray : ['openid'],
        RedirectUriSignIn : 'https://app.domain.com',
        RedirectUriSignOut : 'https://app.domain.com'
    };
    const CognitoAuth = AmazonCognitoIdentity.CognitoAuth;

    const auth = new CognitoAuth(authData);



    auth.userhandler = {
        /**onSuccess: <TODO: your onSuccess callback here>,
         onFailure: <TODO: your onFailure callback here>*/

        onSuccess: function(result: any) {
            console.log("COGNITO SUCCESS!");
            console.log(result);
        },
        onFailure: function(err: any) {
            console.log("COGNITO FAIL!");
            console.log(err);
        }
    };

    auth.getSession();

    const curUrl = window.location.href;
    auth.parseCognitoWebResponse(curUrl);

我现在有一个 auth 对象,我想将其放入我拥有的 aws-sdk 的某种凭证中,这样我就可以将项目列出到 S3 存储桶中,假设我的附加角色中的策略是正确的。

像这样,但意识到这不起作用:

AWS.config.credentials = auth.toCredentials();  //<== hoping for magic
const s3 = new AWS.S3();
s3.listObjectsV2(listObjectsV2Params, function(err: any, data: any) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data.Contents[0]);           // successful response
    });

这可能吗?如果可以,我该怎么做?

UDPATE

接受的答案有效并且帮助很大,为了清楚起见,我 运行 遇到了一些麻烦。

const creds = new AWS.CognitoIdentityCredentials({
                IdentityPoolId: 'us-east-1:b111111-1111-1111-1111-1111111',  // <-- This is in your Federated Identity if you have that set up, you have to "edit" the identity pool to get it, logging into cognito its a different screen.
                Logins: {
                    "cognito-idp.us-east-1.amazonaws.com/us-east-1_BBBB1BBBBV2B": result.idToken.jwtToken  // <- this login [POOL ID] is not the pool ARN, you need it in this format.
                }
            });

this link helped me.

这是可能的,以下是步骤。

  • 要允许 AWS Userpool 用户访问 AWS 资源,还需要配置 AWS Identity Pools 将 UserPool 注册为提供者。
  • 为经过身份验证的用户分配的 IAM 角色需要访问 S3。
  • 使用适用于身份池的 AWS 开发工具包,可以将 UserPools JWT 令牌交换为临时 AccessKey 和 SecretKey,以使用适用于 S3 的 AWS 开发工具包。

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: IDENTITY_POOL_ID,
          Logins: {
            [USER_POOL_TOKEN]: result.idToken.jwtToken
          }
        });
    
        AWS.config.credentials.refresh((error) => {
          if (error) {
            console.error(error);
          } else {
            console.log('Successfully logged!');
          }
        });
    
  • AWS.config.credentials.refresh 回调中,您可以调用 S3,因为该方法内部将处理获取临时凭证。