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

如何使用Node.js和AWS SDK提取Cognito用户池域名

Cognito用户池域名查询方案

你之前调用的describeUserPoolClient是查询用户池下客户端配置的接口,域名属于用户池层级的配置,不会在该接口返回,需要调用用户池详情相关接口获取。

  • 核心可用接口:
    • 单域名场景(绝大多数默认场景,一个用户池只配一个Cognito托管前缀域名):直接调用describeUserPool接口,传入用户池ID即可拿到域名前缀
    • 多域名场景(用户池绑定了多个自定义域名/托管域名):调用listUserPoolDomains接口,传入用户池ID即可拿到该池下所有绑定的域名列表

代码实现(Node.js + AWS SDK)

AWS SDK v2 版本

先安装依赖:
npm install aws-sdk
实现代码:

const AWS = require('aws-sdk');
// 替换为你实际使用的AWS区域,凭证会自动从环境变量、~/.aws/credentials等默认位置加载
const cognitoClient = new AWS.CognitoIdentityServiceProvider({ region: 'us-east-1' });

async function getCognitoOAuthDomain(userPoolId) {
  const { UserPool } = await cognitoClient.describeUserPool({ UserPoolId: userPoolId }).promise();
  // 优先取自定义域名,如果没有配置自定义域名则拼接默认Cognito托管域名
  if (UserPool.CustomDomain) {
    return `https://${UserPool.CustomDomain}`;
  }
  const region = cognitoClient.config.region;
  return `https://${UserPool.Domain}.auth.${region}.amazoncognito.com`;
}

// 调用示例,替换为你自己的用户池ID
getCognitoOAuthDomain('us-east-1_XXXXXXX').then(domain => {
  console.log('OAuth2请求目标域名:', domain);
});

AWS SDK v3 版本(模块化推荐版本)

先安装对应依赖:
npm install @aws-sdk/client-cognito-identity-provider
实现代码:

const {
  CognitoIdentityProviderClient,
  DescribeUserPoolCommand
} = require("@aws-sdk/client-cognito-identity-provider");

// 替换为你实际使用的AWS区域
const cognitoClient = new CognitoIdentityProviderClient({ region: "us-east-1" });

async function getCognitoOAuthDomain(userPoolId) {
  const command = new DescribeUserPoolCommand({ UserPoolId: userPoolId });
  const { UserPool } = await cognitoClient.send(command);
  // 优先取自定义域名,如果没有配置自定义域名则拼接默认Cognito托管域名
  if (UserPool.CustomDomain) {
    return `https://${UserPool.CustomDomain}`;
  }
  const region = await cognitoClient.config.region();
  return `https://${UserPool.Domain}.auth.${region}.amazoncognito.com`;
}

// 调用示例,替换为你自己的用户池ID
getCognitoOAuthDomain('us-east-1_XXXXXXX').then(domain => {
  console.log('OAuth2请求目标域名:', domain);
});

补充说明:如果需要查询用户池下所有域名(包括多个自定义域名、托管域名的场景),把上述代码里的describeUserPool替换为listUserPoolDomains,传入UserPoolId参数后,返回结果里的Domains数组会包含所有绑定域名的完整配置信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:57:11