amazon-web-services - 通过 Amplify Auth 获取登录用户的凭据

标签 amazon-web-services amazon-cognito aws-amplify aws-sdk-js aws-amplify-sdk-js

我正在将 AWS Amplify 用于 ReactJS 应用程序。我使用 Amplify 的唯一两个功能区域是身份验证和托管。这两个工作正常,并且与该项目关联的 Cognito 用户池正在按预期工作,在成功身份验证后将登录的用户提供给 React 组件。

我的下一步是查询 Amplify 配置之外的其他 AWS 资源,从 S3 存储桶和 DynamoDB 表开始。我尝试使用 AWS 客户端 SDK 来实现这些目的,但无法弄清楚如何使用当前登录用户的凭证。

我尝试使用来自 @aws-sdk/credentials-providersfromWebToken,但我没有身份池;我正在使用 Cognito 用户池,因为只有经过身份验证的用户才能访问该 Web 应用程序。所以我对如何继续感到困惑。我的想法是当前的用户凭据将自动用于任何客户端请求,但显然情况并非如此。

这是我的代码;请注意,这只是尝试展示我所尝试的内容,我的问题非常简单:如何获取当前经过身份验证的用户的凭据以与 S3 和其他 AWS 客户端 SDK 组件一起使用? p>

    // user is the currently logged in user. I can see the accessToken etc. here.
    console.log(user.signInUserSession.accessToken);

    const client = new S3Client({
        region: "us-west-2", credentials: fromWebToken({

            clientConfig: {region: "us-west-2"},
            roleArn: "arn:aws:iam::...",  // Got these from IAM for authenticated users
            webIdentityToken: user.signInUserSession.accessToken.jwtToken
        })
    });

我尝试使用客户端下载文件,但出现以下错误:

const command = new GetObjectCommand({
            Bucket: bucket,
            Key: key,
        });
const response = await client.send(command);

// Throws the error: No Cognito Identity pool provided for unauthenticated access

感谢任何帮助。

最佳答案

这实际上是一个三步过程:

  1. 定义一个新的身份池,并将其与来自 Amplify 的经过身份验证的用户池中的登录用户关联。说明位于 https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-integrating-user-pools-with-identity-pools.html

  2. 为 S3 存储桶设置 CORS。直接从 Lambda 函数使用 SDK 时不需要这样做,但对于 Amplify 则需要这样做。说明位于https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html

  3. 配置与身份池关联的策略以授予对 S3 存储桶的访问权限。这是常见的 IAM 策略内容。

我使用了以下库/导入:

import {S3Client, GetObjectCommand} from "@aws-sdk/client-s3";
import {fromCognitoIdentityPool} from "@aws-sdk/credential-providers";
import {Auth} from 'aws-amplify';

const Identity_pool_id = <identity pool ID>;

最后,通过以下代码,我能够正确获取文件:

    Auth.currentSession().then(data => {
        const client = new S3Client({
                region: "us-west-2",
                credentials: fromCognitoIdentityPool({
                    clientConfig: {region: "us-west-2"},
                    identityPoolId: Identity_pool_id,
                    logins: {
                        'cognito-idp.us-west-2.amazonaws.com/<user_pool_id>': data.getIdToken().getJwtToken()
                    }
                })
            }
        );
        try {
            const command = new GetObjectCommand({
                Bucket: bucket,
                Key: key,
                clientConfig: {region: "us-west-2"},
            });
            client.send(command).then(async (data) => {
                // const stats = JSON.parse(data.Body.toString());
                const data2 = await data.Body.transformToString();
                console.log(data2);
            });
        } catch (err) {
            console.log(err);
        }
    });

我希望在没有身份池的情况下完成此操作,因此我不会将其标记为接下来几天的最终答案,以防万一有其他选择。

关于amazon-web-services - 通过 Amplify Auth 获取登录用户的凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74410689/

相关文章:

amazon-web-services - 将 .config 文件传递​​给 AWS Elastic Beanstalk

scala - 如何结束或失败 AWS Glue 作业并出现错误?

oauth-2.0 - AWS Cognito 资源服务器标识符和范围 资源服务器带来

react-native - 从 token 端点检索的 ID token 获取 AWS Cognito 用户

python - 如何使用 Amplify React 在 Python 中的 Post Confirmation Lambda Trigger 中获取 Cognito Identity Id?

php - 处理后从 SQS 队列中删除消息

amazon-web-services - 如何使用 Boto3 将文档上传到 AWS CloudSearch

javascript - AWS Cognito + 谷歌注册

api - AWS Cognito AccessToken 与 IdToken

ios - 更改 Cognito-User-Pool/AWS-Amplify;导致注册问题