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

使用@aws-sdk/client-cognito-identity-provider构造URL失败求助

问题分析与解决方案

问题根源

k6的运行环境基于Go的V8 runtime,并非完整Node.js环境,AWS SDK v3(@aws-sdk/client-cognito-identity-provider)内部依赖的Node.js核心模块(如url的端点解析逻辑)在k6中存在兼容性问题,导致自动根据region生成Cognito端点时失败。

解决方案

方案1:使用k6官方AWS扩展(推荐)

k6提供了专门适配的AWS扩展k6/x/aws,无需依赖Node.js核心模块,直接支持Cognito认证操作:

import { AWSConfig, CognitoIdentityProvider } from 'k6/x/aws/cognitoidentityserviceprovider';

export default async function () {
  const awsConfig = new AWSConfig({
    region: 'eu-west-1',
    // 若依赖环境变量传递凭证,可省略accessKeyId/secretAccessKey,k6会自动读取
    accessKeyId: 'YOUR_ACCESS_KEY',
    secretAccessKey: 'YOUR_SECRET_KEY',
  });

  const cognito = new CognitoIdentityProvider(awsConfig);

  const params = {
    AuthFlow: 'USER_PASSWORD_AUTH',
    ClientId: 'YOUR_COGNITO_CLIENT_ID',
    AuthParameters: {
      USERNAME: 'test-user',
      PASSWORD: 'test-password',
    },
  };

  try {
    const response = await cognito.initiateAuth(params);
    console.log('Auth success:', response.AuthenticationResult.IdToken);
  } catch (err) {
    console.error('Auth failed:', err);
  }
}

方案2:手动指定端点(适配AWS SDK v3)

如果必须使用官方AWS SDK v3,需绕过自动端点解析逻辑,手动指定Cognito服务端点:

import {
  AuthFlowType,
  CognitoIdentityProviderClient,
  InitiateAuthCommand,
} from '@aws-sdk/client-cognito-identity-provider';

export default async function () {
  // 手动指定endpoint,替代SDK自动解析逻辑
  const client = new CognitoIdentityProviderClient({
    region: 'eu-west-1',
    endpoint: 'https://cognito-idp.eu-west-1.amazonaws.com',
  });

  const params = {
    AuthFlow: AuthFlowType.USER_PASSWORD_AUTH,
    ClientId: 'YOUR_COGNITO_CLIENT_ID',
    AuthParameters: {
      USERNAME: 'test-user',
      PASSWORD: 'test-password',
    },
  };

  try {
    const command = new InitiateAuthCommand(params);
    const response = await client.send(command);
    console.log('Auth command sent successfully');
    console.log('IdToken:', response.AuthenticationResult.IdToken);
  } catch (err) {
    console.error('Auth failed:', err);
  }
}

额外注意事项

  • k6中运行异步代码需确保在export default函数内使用async/await,符合k6的测试执行逻辑。
  • 若使用IAM权限认证,需确保k6运行环境的AWS凭证配置正确(环境变量、~/.aws/credentials等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 12:42:09