使用Auth.js与AWS Cognito SRP流时,如何捕获返回登录错误信息
问题:Auth.js集成AWS Cognito SRP流时无法返回具体错误信息
我正在使用AWS Cognito的SRP(安全远程密码)认证流实现自定义登录和注册页面,采用Auth.js(原NextAuth)的凭证提供方方法处理会话与登录。
在Next.js 15+的普通API路由中,登录功能运行正常,但将其集成到Auth.js凭证提供方的authorize函数时,输入无效邮箱或密码会出现如下错误:
[auth][error] CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror [auth][cause]: invalid user name and password
我尝试过抛出错误和处理异常,但响应中并未返回具体错误信息,而是返回{code:config}。我必须使用Auth.js,无法回退到NextAuth v4,且因错误类型众多(如“用户未验证”等),无法通过switch-case手动处理。
请问是否有方法能在使用Auth.js与AWS Cognito SRP认证流时,正确捕获并返回具体错误信息?
解决方案
1. 拆分SRP认证与Auth.js会话创建
保留SRP认证逻辑在独立API路由(如/api/auth/cognito-srp),该路由直接返回Cognito的具体错误信息,再在自定义登录页中处理:
- 登录页调用该API完成SRP认证,若失败直接展示返回的错误(如
{ error: "invalid user name and password" }或{ error: "user not verified" }); - 若认证成功,再调用Auth.js的
signIn("credentials", { ...用户信息, redirect: false })创建会话。
2. 在authorize中传递具体错误
捕获Cognito SRP返回的原始错误,将其作为自定义Error对象的消息抛出,前端通过Auth.js的登录返回结果获取:
import Credentials from "@auth/core/providers/credentials"; export const { auth } = NextAuth({ providers: [ Credentials({ async authorize(credentials) { try { // 执行AWS Cognito SRP认证逻辑 const user = await cognitoSrpAuth(credentials.email, credentials.password); return user; } catch (err) { // 提取Cognito返回的具体错误内容 const specificError = err.message || err.response?.data?.error || "登录失败"; // 抛出包含具体信息的错误 throw new Error(specificError); } }, }), ], pages: { signIn: "/login", // 指向自定义登录页 }, });
在自定义登录页中捕获错误:
"use client"; import { signIn } from "next-auth/react"; import { useState } from "react"; export default function LoginPage() { const [loginError, setLoginError] = useState(""); const handleLogin = async (e) => { e.preventDefault(); const formData = new FormData(e.target); const result = await signIn("credentials", { email: formData.get("email"), password: formData.get("password"), redirect: false, }); if (result?.error) { setLoginError(result.error); // 这里拿到具体错误信息 } else { window.location.href = "/"; } }; return ( <div> {loginError && <p className="text-red-500">{loginError}</p>} <form onSubmit={handleLogin}> <input type="email" name="email" required /> <input type="password" name="password" required /> <button type="submit">登录</button> </form> </div> ); }
3. 后端错误日志(可选)
通过Auth.js的events钩子记录原始错误,便于排查:
export const { auth } = NextAuth({ // ...其他配置 events: { async error({ error, message }) { // 将错误信息写入日志服务 console.log("Auth 错误详情:", message, error.cause); }, }, });
内容的提问来源于stack exchange,提问作者Sundar Gopal Nag
相关产品推荐
相关产品推荐

