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

React+AWS Cognito+Amplify:登录后无法验证已注册用户

解决AWS Amplify Hosted UI/第三方登录后Auth.currentAuthenticatedUser()未识别用户的问题

核心问题本质

Hosted UI或第三方登录完成重定向后,Amplify需要主动处理Cognito返回的授权码,完成令牌交换并将会话存储到本地,否则Auth.currentAuthenticatedUser()无法读取到有效会话。


具体解决方案

1. 重定向后必须处理会话交换

登录成功重定向回应用时,要立即调用Auth.federatedSignIn()处理URL中的code和state参数,完成认证流程:

import { useEffect } from 'react';
import { Auth } from 'aws-amplify';

function App() {
  useEffect(() => {
    const processAuthRedirect = async () => {
      const searchParams = new URLSearchParams(window.location.search);
      const authCode = searchParams.get('code');
      const authState = searchParams.get('state');

      if (authCode && authState) {
        try {
          // 完成令牌交换,存储会话
          await Auth.federatedSignIn({ state: authState, code: authCode });
          // 清理URL中的认证参数,避免重复处理
          window.history.replaceState({}, document.title, window.location.pathname);
        } catch (error) {
          console.error('会话处理失败:', error);
        }
      }
    };

    processAuthRedirect();
  }, []);

  // 其他组件逻辑...
}

2. 核对Amplify OAuth配置

确保aws-exports.js中的OAuth配置和Cognito控制台的应用客户端设置完全一致:

export default {
  Auth: {
    region: '你的区域',
    userPoolId: '你的用户池ID',
    userPoolWebClientId: '你的应用客户端ID',
    oauth: {
      domain: '你的Cognito域名.auth.你的区域.amazoncognito.com',
      scope: ['email', 'openid', 'profile'],
      redirectSignIn: 'http://localhost:3000/你的重定向页面', // 必须和Cognito允许的回调URL一致
      redirectSignOut: 'http://localhost:3000/',
      responseType: 'code' // 授权码流程,Hosted UI默认使用这个类型
    }
  }
};

注意:Cognito控制台的“应用客户端设置”中,必须添加上述redirectSignIn和redirectSignOut为允许的回调URL,否则会被拒绝认证。

3. 邮箱密码登录的会话检查

邮箱密码登录时,确保直接使用Auth.signIn(),不要自定义会话存储逻辑干扰Amplify的默认行为:

const handleEmailPasswordLogin = async (username, password) => {
  try {
    const user = await Auth.signIn(username, password);
    // 登录成功后Amplify会自动存储会话,无需额外操作
    console.log('登录用户:', user);
  } catch (error) {
    console.error('登录失败:', error);
  }
};

4. 确保Amplify初始化时机正确

在应用入口文件(比如index.js)最顶部初始化Amplify,避免Auth方法调用时配置未加载:

import Amplify from 'aws-amplify';
import awsExports from './aws-exports';

// 先初始化Amplify,再渲染应用
Amplify.configure(awsExports);

ReactDOM.render(<App />, document.getElementById('root'));

5. 排查浏览器存储限制

  • 如果浏览器开启了第三方Cookie阻止,Amplify无法存储会话。可以在Cognito控制台的“App客户端设置”→“Cookie设置”中开启“防止第三方Cookie”兼容模式;
  • 确保应用域名和Cognito域名的Cookie共享配置正确,比如主域一致或配置了适当的Cookie域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:22:27