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

Amplify Gen 2:如何在Angular应用中列出所有注册用户及角色?

在Angular + Amplify Gen 2中实现用户列表管理页面

Amplify前端SDK不提供直接获取所有Cognito用户的接口,必须通过Lambda调用Cognito Admin API,再通过API Gateway暴露给前端,以下是完整实现步骤:

1. 编写Lambda函数(获取用户及角色)

给Lambda分配AmazonCognitoReadOnly权限(或自定义权限,至少包含listUsers和listGroupsForUser操作),示例Node.js代码:

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

const client = new CognitoIdentityProviderClient({ region: process.env.REGION });
const userPoolId = process.env.USER_POOL_ID;

export const handler = async (event) => {
  // 校验调用者权限(仅允许管理员组访问)
  const userGroups = event.requestContext.authorizer?.claims['cognito:groups'];
  if (!userGroups?.includes('Admin')) {
    return { statusCode: 403, body: JSON.stringify({ error: '无访问权限' }) };
  }

  try {
    // 获取所有用户
    const { Users } = await client.send(new ListUsersCommand({ UserPoolId: userPoolId }));
    // 为每个用户关联所属组(角色)
    const usersWithRoles = await Promise.all(
      Users.map(async (user) => {
        const { Groups } = await client.send(new ListGroupsForUserCommand({
          UserPoolId: userPoolId,
          Username: user.Username
        }));
        return {
          username: user.Username,
          email: user.Attributes.find(attr => attr.Name === 'email')?.Value,
          roles: Groups?.map(g => g.GroupName) || []
        };
      })
    );
    return { statusCode: 200, body: JSON.stringify(usersWithRoles) };
  } catch (err) {
    return { statusCode: 500, body: JSON.stringify({ error: err.message }) };
  }
};

2. 通过Amplify Gen 2配置API路由

在amplify/data/resource.ts中定义查询接口:

import { type ClientSchema, a, defineData } from '@aws-amplify/backend';

const schema = a.schema({
  ListAllUsers: a.query()
    .handler(a.handler.function('listUsersLambda')) // 关联上述Lambda函数
    .authorization(allow => allow.authenticated()) // 仅允许已认证用户调用
});

export const data = defineData({
  schema,
  authorizationModes: { defaultAuthorizationMode: 'userPool' },
});

3. Angular前端调用接口

在Angular组件中生成Amplify客户端并调用查询:

import { generateClient } from 'aws-amplify/data';
import { schema } from '../../amplify/data/resource';

const client = generateClient<typeof schema>();

// 组件内加载用户列表的方法
async loadAllUsers() {
  try {
    const { data: users } = await client.queries.ListAllUsers();
    this.userList = users;
  } catch (error) {
    console.error('加载用户失败:', error);
  }
}

4. 部署与验证

  • 运行amplify push部署后端资源
  • 在Angular应用中确保已正确配置Amplify,调用loadAllUsers方法即可获取带角色的用户列表

内容的提问来源于stack exchange,提问作者Luis Alberto Murcia Solivella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:10:02