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

如何通过JavaScript API获取AWS Amplify用户管理页的全部用户

使用AWS Amplify获取用户管理列表中所有用户的解决方案

你提到的listUsers确实是正确的方向,但需要注意:Amplify的前端Auth模块本身没有直接提供这个方法,因为获取所有用户属于管理员级操作,需要调用Amazon Cognito Identity Provider的官方API来实现。以下是具体的实现步骤和代码示例:


1. 核心依赖与权限准备

  • 确保你的项目已配置AWS Amplify Auth模块,并且具备调用cognito-idp:ListUsers的权限(建议通过后端Lambda封装,避免前端暴露敏感权限;如果必须前端调用,需给当前用户/角色配置对应IAM权限)。
  • 安装AWS SDK的Cognito客户端:
    npm install @aws-sdk/client-cognito-identity-provider
    

2. 实现获取所有用户的JavaScript函数

通过Amplify配置获取用户池信息,初始化Cognito客户端后调用ListUsers API,提取用户邮箱:

import { CognitoIdentityProviderClient, ListUsersCommand } from "@aws-sdk/client-cognito-identity-provider";
import { Auth } from 'aws-amplify';

// 初始化Cognito客户端
const getCognitoClient = async () => {
  const authConfig = await Auth.configure().Auth;
  return new CognitoIdentityProviderClient({ region: authConfig.region });
};

// 获取所有用户邮箱的函数
export const fetchAllUserEmails = async () => {
  const client = await getCognitoClient();
  const { userPoolId } = await Auth.configure().Auth;

  // 构建ListUsers命令,可添加过滤条件(示例:仅返回有邮箱的用户)
  const listUsersCmd = new ListUsersCommand({
    UserPoolId: userPoolId,
    Filter: "email_exists = true"
  });

  try {
    const response = await client.send(listUsersCmd);
    // 从用户属性中提取邮箱
    return response.Users.map(user => {
      const emailAttr = user.Attributes.find(attr => attr.Name === 'email');
      return emailAttr ? emailAttr.Value : '未设置邮箱';
    });
  } catch (err) {
    console.error('获取用户列表失败:', err);
    throw err;
  }
};

3. 关键注意事项

  • 分页处理:Cognito的ListUsers默认最多返回60条用户数据,如果你的用户数量超过这个限制,需要通过响应中的PaginationToken循环调用,直到获取全部数据。
  • 权限安全:前端直接调用此API会暴露管理员权限风险,更推荐的做法是将这个逻辑封装在AWS Lambda函数中,前端通过Amplify API模块调用Lambda,由Lambda执行ListUsers操作。
  • Amplify版本兼容:如果使用Amplify v1,需调整SDK导入方式,但核心逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:05:22