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

Next-Auth signIn方法始终返回true的问题求助

NextAuth凭据登录始终返回成功的问题

我在Next.js项目中集成NextAuth时遇到异常:无论输入的邮箱和密码是否正确,signIn方法始终返回true且无错误提示,无法正确验证登录状态。

登录页代码

'use client'
import React from 'react';
import { useState } from 'react';
import { redirect, useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';

export default function LoginPage() {
    const router = useRouter();
    const [data, setData] = useState({
        email: '',
        password: '',
    });

    const loginUser = async (e) => {
        e.preventDefault();
        console.log("Entered login user");
        console.log(data);
    
        const result = await signIn("credentials", {
            ...data,
            redirect: false,
        });
    
        if (result.error) {
            // Handle sign-in error
            console.error(result.error);
        } else {
            console.log("Sign-in successful")
            console.log(result)
            // Sign-in successful, redirect to the dashboard
            //router.push('/dashboard');
        }
    }
// 省略其余代码

NextAuth配置代码(api/auth/[...nextauth]/route.js)

import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'text' },
        password: { label: 'Password', type: 'password' }
      },
      async authorize(credentials) {
        // Check if email and password are provided
        if (!credentials.email || !credentials.password) {
          return null;
        }

        // Check if the email exists
        const user = await prisma.user.findUnique({
          where: { email: credentials.email }
        });

        // If email doesn't exist, return null
        if (!user) {
          return null;
        }

        // Check if the password is correct
        const passwordsMatch = await bcrypt.compare(
          credentials.password,
          user.hashedPassword
        );

        // If passwords don't match, return null
        if (!passwordsMatch) {
          return null;
        }

        // Return user if email and password are valid
        return user;
      }
    })
  ],
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET,
  debug: process.env.NODE_ENV === "development",
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

问题原因及解决方案

问题核心

NextAuth的CredentialsProvider中,authorize函数返回null时,不会自动触发错误提示。在redirect: false的模式下,signIn会默认返回{ ok: true },导致错误判断登录状态。

修复步骤

修改authorize函数,将返回null的逻辑改为抛出错误,这样signIn就能捕获到错误信息并返回result.error:

async authorize(credentials) {
  // 检查邮箱和密码是否存在
  if (!credentials.email || !credentials.password) {
    throw new Error("请填写邮箱和密码");
  }

  // 查询用户
  const user = await prisma.user.findUnique({
    where: { email: credentials.email }
  });

  // 用户不存在时抛出错误
  if (!user) {
    throw new Error("该邮箱未注册");
  }

  // 验证密码
  const passwordsMatch = await bcrypt.compare(
    credentials.password,
    user.hashedPassword
  );

  // 密码不匹配时抛出错误
  if (!passwordsMatch) {
    throw new Error("密码错误");
  }

  // 验证通过返回用户信息
  return user;
}

额外提示

  • 确保NEXTAUTH_SECRET环境变量已正确配置,这是JWT会话正常工作的必要条件。
  • 开发环境下开启debug: true可以查看NextAuth详细日志,辅助排查其他潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:15:32