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

配置ssr:true后AWS Amplify Auth调用signIn抛出UserUnAuthenticatedException问题排查

Amplify SSR场景下登录报错 User needs to be authenticated to call this API 的问题排查

可能的原因及修复方案

1. signIn 函数导入错误

确认你从正确的Auth模块导入signIn,错误的导入可能导致调用了需要前置认证的API:

// 正确导入方式
import { signIn } from 'aws-amplify/auth';

如果之前是从旧路径(如aws-amplify直接导入),可能引发不兼容问题,建议切换到上述模块化导入。

2. 登录逻辑运行在服务器端

登录是客户端专属操作,服务器端没有浏览器的会话存储,无法处理signIn的状态同步。如果你的login函数是在服务器组件(比如Next.js中未标记'use client'的组件)中执行,会触发该错误。

解决:将登录逻辑移到客户端组件中,比如在Next.js里添加'use client'指令:

'use client';

import { signIn } from 'aws-amplify/auth';
import { useRouter } from 'next/navigation';

async function login(email, password) {
    try {
        console.log(email, password);
        const user = await signIn({ username: email, password: password });
        console.log(user);
        if (user.isSignedIn) {
            const router = useRouter();
            router.push('/admin');
        }
    } catch (error) {
        console.log('error signing in', error);
    }
}

3. Amplify SSR配置不完整

仅设置ssr: true不足以处理SSR场景的会话同步,若需要在服务器端获取认证状态,需使用Amplify的withSSRContext工具:

import { withSSRContext } from 'aws-amplify/auth/server';

// 服务器端获取用户状态示例(如Next.js的getServerSideProps)
export async function getServerSideProps(context) {
  const { Auth } = withSSRContext(context);
  try {
    const user = await Auth.currentAuthenticatedUser();
    return { props: { user: JSON.parse(JSON.stringify(user)) } };
  } catch (err) {
    return { props: { user: null } };
  }
}

4. 配置文件或用户池设置错误

检查amplifyconfiguration.json中的Auth配置,确保:

  • aws_user_pools_id、aws_user_pools_web_client_id与AWS控制台中用户池的信息完全一致。
  • 用户池客户端未启用不必要的"仅允许已认证用户访问"限制。

5. 残留会话数据干扰

浏览器本地存储中的无效Amplify会话数据可能导致认证逻辑混乱,清除以下相关存储项后重试:

  • amplify-signin-with-hostedUI
  • CognitoIdentityServiceProvider-<你的客户端ID>相关键值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:05:04