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

页面刷新后Auth.currentUserInfo()返回null的问题求助

解决AWS Amplify Auth刷新后currentUserInfo()返回null的问题
  • 检查Auth持久化配置
    确保Amplify初始化时配置持久化存储为localStorage(默认可能是sessionStorage,页面刷新后会丢失会话数据):

    import { Amplify } from 'aws-amplify';
    import awsconfig from './aws-exports';
    
    Amplify.configure({
      ...awsconfig,
      Auth: {
        ...awsconfig.Auth,
        storage: window.localStorage // 改为localStorage持久化会话
      }
    });
    
  • 替换currentUserInfo()为currentAuthenticatedUser()
    Auth.currentUserInfo()仅读取本地缓存的基础用户信息,一旦缓存失效就会返回null。Auth.currentAuthenticatedUser()会主动尝试从Cognito刷新会话并拉取完整用户信息,更适合页面刷新后的场景:

    const getCurrentUser = async () => {
      try {
        const user = await Auth.currentAuthenticatedUser({ bypassCache: false });
        // 若需要实时最新数据,可将bypassCache设为true,强制从Cognito拉取
        return user;
      } catch (error) {
        console.error('获取用户失败:', error);
        return null;
      }
    };
    
  • 验证自定义挑战流程的会话完整性
    在调用Auth.sendCustomChallengeAnswer后,确认返回的authUser对象包含有效会话:

    Auth.sendCustomChallengeAnswer(authUser, code)
      .then(user => {
        console.log('用户认证会话:', user.signInUserSession);
        // 若signInUserSession存在,说明会话已正确建立
      })
      .catch(err => console.error('挑战验证失败:', err));
    

    若会话未生成,检查自定义挑战Lambda触发器的返回值是否符合Cognito要求(需正确返回challengeResult: true等必要参数)。

  • 检查Cognito用户池应用客户端设置

    1. 进入AWS控制台的Cognito用户池
    2. 找到对应的应用客户端,确保启用了允许刷新令牌
    3. 确认刷新令牌有效期设置合理(默认30天),避免会话过早失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:01:00