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

AWS Cognito ListUsers API使用咨询:React管理端用户列表展示

解决方法:在React中用AWS Cognito AdminListUsers API实现管理员查看用户列表及自定义属性

Got it, let's break this down step by step since you already have your Cognito user pool, groups, and users in place. The key here is using the AdminListUsers API (not the regular ListUsers, which is intended for backend/developer use) because you want an authenticated admin user to fetch the list from your React app.


1. 先确保管理员有正确的IAM权限

First, your admin user/group needs permission to call cognito-idp:AdminListUsers. Here's how to set that up:

  • Go to the IAM console, create a new policy with this JSON:
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "cognito-idp:AdminListUsers",
          "Resource": "arn:aws:cognito-idp:YOUR_REGION:YOUR_ACCOUNT_ID:userpool/YOUR_USER_POOL_ID"
        }
      ]
    }
    
  • Attach this policy to the IAM role associated with your admin group (or directly to the admin user if you're using IAM users, though groups are better practice).

2. 在React项目中配置AWS依赖

Install the necessary packages:

npm install @aws-amplify/auth @aws-sdk/client-cognito-identity-provider

Then configure Amplify in your app (usually in src/index.js or a dedicated config file):

import { Amplify } from 'aws-amplify';

Amplify.configure({
  Auth: {
    region: 'YOUR_REGION',
    userPoolId: 'YOUR_USER_POOL_ID',
    userPoolWebClientId: 'YOUR_APP_CLIENT_ID',
  },
});

3. 实现管理员登录验证

First, build a login component that checks if the authenticated user is in the admin group after sign-in:

import { useState } from 'react';
import { Auth } from '@aws-amplify/auth';

const AdminLogin = ({ onAdminLogin }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    try {
      const user = await Auth.signIn(email, password);
      // 检查用户是否属于管理员组
      const userGroups = user.signInUserSession.accessToken.payload['cognito:groups'] || [];
      if (userGroups.includes('YOUR_ADMIN_GROUP_NAME')) {
        onAdminLogin(user);
      } else {
        alert('You are not authorized to access this page');
        await Auth.signOut();
      }
    } catch (err) {
      console.error('Login error:', err);
      alert('Login failed: ' + err.message);
    }
  };

  return (
    <div>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Admin Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button onClick={handleLogin}>Admin Login</button>
    </div>
  );
};

export default AdminLogin;

4. 调用AdminListUsers API获取用户列表

Create a function to fetch users using the authenticated admin's credentials. We'll use the AWS SDK's CognitoIdentityProviderClient:

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

const fetchCognitoUsers = async () => {
  try {
    // 获取当前登录用户的凭证
    const credentials = await Auth.currentCredentials();
    const client = new CognitoIdentityProviderClient({
      region: 'YOUR_REGION',
      credentials: {
        accessKeyId: credentials.accessKeyId,
        secretAccessKey: credentials.secretAccessKey,
        sessionToken: credentials.sessionToken,
      },
    });

    // 构建AdminListUsers命令
    const command = new AdminListUsersCommand({
      UserPoolId: 'YOUR_USER_POOL_ID',
      // 可选:过滤用户(比如只看普通用户组,不过后面也可以在前端过滤)
      // Filter: 'cognito:groups = "YOUR_REGULAR_USER_GROUP_NAME"'
    });

    const response = await client.send(command);
    return response.Users;
  } catch (err) {
    console.error('Error fetching users:', err);
    throw err;
  }
};

5. 过滤普通用户并提取自定义属性

Once you have the user list, filter for users in your regular group and extract their custom attributes (which start with custom:):

import { useState, useEffect } from 'react';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUsers = async () => {
      try {
        const allUsers = await fetchCognitoUsers();
        // 过滤普通用户组的用户
        const regularUsers = allUsers.filter(user => {
          const groups = user.Attributes.find(attr => attr.Name === 'cognito:groups');
          return groups?.Value.includes('YOUR_REGULAR_USER_GROUP_NAME');
        });

        // 整理用户数据,提取自定义属性
        const formattedUsers = regularUsers.map(user => {
          const customAttributes = user.Attributes.reduce((acc, attr) => {
            if (attr.Name.startsWith('custom:')) {
              acc[attr.Name.replace('custom:', '')] = attr.Value;
            }
            return acc;
          }, {});

          return {
            username: user.Username,
            email: user.Attributes.find(attr => attr.Name === 'email')?.Value,
            ...customAttributes,
          };
        });

        setUsers(formattedUsers);
      } catch (err) {
        console.error('Failed to load users:', err);
      } finally {
        setLoading(false);
      }
    };

    loadUsers();
  }, []);

  if (loading) return <div>Loading users...</div>;

  return (
    <div>
      <h2>Regular Users List</h2>
      <table>
        <thead>
          <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Custom Attribute 1</th>
            <th>Custom Attribute 2</th>
            {/* 添加你自定义的属性列 */}
          </tr>
        </thead>
        <tbody>
          {users.map(user => (
            <tr key={user.username}>
              <td>{user.username}</td>
              <td>{user.email}</td>
              <td>{user.yourCustomAttr1}</td>
              <td>{user.yourCustomAttr2}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default UserList;

6. 处理分页(可选)

If you have more than 60 users, AdminListUsers will return a PaginationToken. You can handle this by adding a "Load More" button that fetches the next page:

// 在fetchCognitoUsers函数中添加paginationToken参数
const fetchCognitoUsers = async (paginationToken = null) => {
  // ...
  const command = new AdminListUsersCommand({
    UserPoolId: 'YOUR_USER_POOL_ID',
    PaginationToken: paginationToken,
  });
  // ...
};

// 在UserList组件中管理paginationToken状态,实现加载更多

关键注意事项

  • 权限检查: 确保你的 admin 用户/group 确实有 cognito-idp:AdminListUsers 权限,否则你会得到 403 错误。
  • 自定义属性: 确保这些属性已经在你的 Cognito 用户池的"属性"设置中被创建为可读写(或只读,根据你的需求)。
  • 会话过期: 处理用户会话过期的情况,比如在 API 调用失败时重定向到登录页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:09:15