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

如何使用fromCognitoIdentityPool刷新AWS SDK JS V3客户端凭证?

解决方案:AWS SDK JS V3 + fromCognitoIdentityPool 自动刷新凭证

核心思路是让fromCognitoIdentityPool的logins配置动态获取最新IDToken,而非初始化时的静态值。AWS SDK V3的凭证提供程序会在需要刷新凭证时自动调用logins中的异步函数,从而获取有效token。

步骤1:改造AuthService,支持自动刷新IDToken

确保你的认证服务能检查IDToken是否过期,过期则自动刷新并返回最新token:

// auth.service.ts
import { CognitoUser, CognitoUserPool, CognitoUserSession } from 'amazon-cognito-identity-js';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private userPool: CognitoUserPool;

  constructor() {
    this.userPool = new CognitoUserPool({
      UserPoolId: environment.cognito.userPoolId,
      ClientId: environment.cognito.clientId
    });
  }

  async getIdToken(): Promise<string> {
    const currentUser = this.userPool.getCurrentUser();
    if (!currentUser) {
      throw new Error('无活跃用户会话');
    }

    // 获取当前会话
    const currentSession = await new Promise<CognitoUserSession>((resolve, reject) => {
      currentUser.getSession((err, session) => {
        if (err) reject(err);
        else resolve(session!);
      });
    });

    // 检查IDToken是否即将过期(提前5分钟触发刷新)
    const tokenExpiryTime = currentSession.getIdToken().getExpiration() * 1000;
    const isTokenExpired = tokenExpiryTime < Date.now() + 5 * 60 * 1000;

    if (isTokenExpired) {
      // 使用Refresh Token刷新会话
      const refreshedSession = await new Promise<CognitoUserSession>((resolve, reject) => {
        currentSession.refreshSession(currentSession.getRefreshToken(), (err, session) => {
          if (err) reject(err);
          else resolve(session!);
        });
      });

      // 保存刷新后的会话
      currentUser.setSession(refreshedSession);
      return refreshedSession.getIdToken().getJwtToken();
    }

    return currentSession.getIdToken().getJwtToken();
  }
}

步骤2:实例化Cognito客户端,配置动态logins

只需实例化一次客户端,logins中传入异步函数获取最新token:

// 你的业务服务/组件中
import { CognitoIdentityProviderClient } from "@aws-sdk/client-cognito-identity-provider";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";

this.cognitoClient = new CognitoIdentityProviderClient({
  region: environment.cognito.region,
  credentials: fromCognitoIdentityPool({
    clientConfig: { region: environment.cognito.region },
    identityPoolId: environment.cognito.identityPoolId,
    logins: {
      // 用异步函数动态获取最新IDToken
      [`cognito-idp.${environment.cognito.region}.amazonaws.com/${environment.cognito.userPoolId}`]: async () => this.authService.getIdToken()
    }
  })
});

关键说明

  • AWS SDK V3的fromCognitoIdentityPool会在凭证过期时自动触发刷新逻辑,此时会调用logins中的异步函数获取最新IDToken,无需手动重新实例化客户端。
  • 确保Cognito用户池的App Client已开启允许使用Refresh Token(在用户池控制台的App Client设置中启用)。
  • 提前5分钟触发刷新是为了避免token在请求过程中过期,可根据业务调整时间阈值。

内容的提问来源于stack exchange,提问作者Alex C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:30:39