You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue Amplify Gen1应用中通过登录用户角色用AWS SDK列出Cognito用户池用户

问题分析与解决方案

你用fromCognitoIdentity的参数配置确实存在问题,这个方法不能直接硬填identityId和customRoleArn来获取有效凭证,它需要依赖Cognito身份池的完整认证流程生成临时凭证。在Vue Amplify Gen1场景下,正确的做法是利用Amplify内置的凭证管理能力,无需手动构造凭证。

核心问题

fromCognitoIdentity的设计是从Cognito身份池获取临时凭证,但你未提供获取凭证的必要前置信息(比如身份池ID、已登录用户的ID Token等),直接填固定值会导致SDK无法获取有效凭证,从而抛出"Missing credentials in config"错误。

正确实现步骤

  1. 确保Amplify已初始化
    在项目入口文件(如main.js)中完成Amplify基础配置:

    import Amplify from 'aws-amplify';
    import awsconfig from './aws-exports';
    Amplify.configure(awsconfig);
    
  2. 通过Amplify获取当前用户凭证
    无需手动设置credentials,直接调用Amplify的Auth.currentCredentials()获取当前登录用户的临时凭证,自动关联其绑定的IAM角色权限:

    import { Auth } from 'aws-amplify';
    import AWS from 'aws-sdk';
    
    // 封装Cognito客户端获取逻辑
    const getCognitoClient = async () => {
      const credentials = await Auth.currentCredentials();
      AWS.config.update({
        credentials: credentials,
        region: 'ap-southeast-2'
      });
      return new AWS.CognitoIdentityServiceProvider();
    };
    
    // 获取用户列表的异步函数
    const fetchUsers = async () => {
      loadingRef.value = true;
      try {
        const cognito = await getCognitoClient();
        const params = {
          UserPoolId: 'ap-southeast-2_Wc***ww',
        };
        const data = await cognito.listUsers(params).promise();
        users.value = data.Users;
        realData.value = transformUsersToArray(data.Users!);
        origData = transformUsersToArray(data.Users!);
        console.log("real data is :", realData);
        console.log(data.Users);
      } catch (error) {
        console.error('Error fetching users:', error);
      } finally {
        loadingRef.value = false;
      }
    };
    
  3. 验证IAM角色权限
    确保当前登录用户绑定的IAM角色(身份池的认证角色)已附加允许cognito-idp:ListUsers的策略:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "cognito-idp:ListUsers",
          "Resource": "arn:aws:cognito-idp:ap-southeast-2:89***6347:userpool/ap-southeast-2_Wc***ww"
        }
      ]
    }
    

为什么原来的方式不行?

硬编码accessKeyId和secretAccessKey是使用长期凭证,存在安全风险;而fromCognitoIdentity需要依赖身份池的认证流程(比如用用户的ID Token换取临时凭证),你直接传入固定的identityId和roleArn,SDK无法完成临时凭证的生成流程,因此报错。

内容的提问来源于stack exchange,提问作者benihamalu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:40:04