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

使用Cognito JS SDK v3创建客户端后,client_credentials模式无法获取Token

问题:AWS Cognito client_credentials模式获取Token报invalid_grant错误

已使用AWS Cognito Identity Provider Client SDK for JavaScript v3(执行命令npm install @aws-sdk/client-cognito-identity-provider)创建用户池客户端与资源服务器,代码如下:

let poolName = 'UserPool';
const client = new CognitoIdentityProviderClient({
          region: process.env.COGNITO_AWS_REGION
      });
// 创建资源服务器
const createResourceServerCommand = new CreateResourceServerCommand({
  Name: poolName,
  UserPoolId: UserPool.Id,
  Identifier: 'https://localhost:8080/api/v2',
  Scopes: [
    {
      ScopeName: 'access',
      ScopeDescription: 'General access to API'
    }
  ]
});

const { ResourceServer } = await client.send(createResourceServerCommand);
// 创建用户池客户端
const createUserPoolClientCommand = new CreateUserPoolClientCommand({
  ClientName: 'Default',
  UserPoolId: UserPool.Id,
  ExplicitAuthFlows: ['USER_PASSWORD_AUTH'],
  GenerateSecret: true,
  AllowedOAuthFlows: ['client_credentials'],
  SupportedIdentityProviders: ['COGNITO'],
  AllowedOAuthScopes: [ 'https://localhost:8080/api/v2/access' ]
});
const { UserPoolClient } = await client.send(createUserPoolClientCommand);

调用client_credentials授权类型获取Token时,报错:

{
  "error": "invalid_grant"
}

但通过AWS控制台进入「用户池 > 客户端 > 编辑托管UI」,无需修改任何设置直接点击保存按钮后,即可正常通过client_credentials模式获取Token。需要确认代码中是否遗漏了控制台自动设置的配置项,以实现用户池的自动化创建。


解决方案

问题出在代码中未设置AllowedOAuthFlowsUserPoolClient参数,该参数默认值为false,而控制台保存操作会自动将其设为true。这个参数的作用是启用用户池客户端与指定OAuth流的关联,没有开启的话,client_credentials授权流无法正常生效。

修改后的用户池客户端创建代码如下:

const createUserPoolClientCommand = new CreateUserPoolClientCommand({
  ClientName: 'Default',
  UserPoolId: UserPool.Id,
  ExplicitAuthFlows: ['USER_PASSWORD_AUTH'],
  GenerateSecret: true,
  AllowedOAuthFlows: ['client_credentials'],
  SupportedIdentityProviders: ['COGNITO'],
  AllowedOAuthScopes: [ 'https://localhost:8080/api/v2/access' ],
  // 新增配置:启用用户池客户端的OAuth流支持
  AllowedOAuthFlowsUserPoolClient: true
});
const { UserPoolClient } = await client.send(createUserPoolClientCommand);

添加AllowedOAuthFlowsUserPoolClient: true后,客户端就能正常通过client_credentials授权类型获取Token,无需再手动通过控制台保存配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:10:25