NextAuth 授权用户但用户信息为空

NextAuth authorizes user but user info is null

我正在尝试使用凭据(电子邮件和密码)实施 NextAuth。
我为此设置了 mongodb。我还设置了 /api/proile/ 到 post 登录凭据的路由,并使用 Postman,returns 用户正确测试了它。


但问题是在登录后开始的。当我登录时,vscode 终端中的凭据 return (我控制台登录 /api/auth/[...nextauth].js 使用 console.log(credentials) 但在浏览器中它授权用户,我可以访问和查看受保护的路由和内容,但是当我在前端登录会话时,它显示为 null 用户信息,如您所见下图;

这是我的 /api/auth/[...nextauth].js 代码;

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { connectToDatabase } from '../../../util/mongodb';

const options = {
  providers: [
 
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        console.log(credentials);
        const res = await fetch('http://localhost:3000/api/profile/', {
          method: 'POST',
          body: JSON.stringify(credentials),
          headers: {
            'Content-Type': 'application/json',
          },
        });
        const user = await res.json();

        // const user = { id: '1', name: 'Suat Bayrak', email: 'test@test.com2' };

        if (user) {
          return user;
        } else {
          return null;
        }
      },
    }),
  ],
  pages: {
    signIn: '/signin',
  },
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,
    updateAge: 24 * 60 * 60,
  },


  database:             `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-    sb.ki5vd.mongodb.net/test`,
};

export default (req, res) => NextAuth(req, res, options);

顺便说一句,当我像我在上面的代码中评论的那样使用静态用户凭据时,它工作得很好并且 returns 会话信息正确...

这也是我的 /pages/signin.js

import { signIn } from 'next-auth/client';
import { useState } from 'react';
import { useRouter } from 'next/router';

export default function SignIn() {
  const router = useRouter();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loginError, setLoginError] = useState('');
  const handleSubmit = async (e) => {
    e.preventDefault();

    console.log('submitted!');
    signIn('credentials', {
      email: email,
      password: password,
      //   email: 'test@test.com',
      //   password: '1234',
      callbackUrl: 'http://localhost:3000/about',
      redirect: false,
    }).then(function (result) {
      console.log(result);
      if (result.error !== null) {
        if (result.status === 401) {
      setLoginError(
        'Your username/password combination was incorrect. Please try again'
      );
    } else {
      setLoginError(result.error);
    }
  } else {
    console.log(result);
    router.push(result.url);
  }
});
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input
          name='email'
          type='text'
      value={email}
      onChange={(e) => setEmail(e.target.value)}
    />
  </label>
  <label>
    Password
    <input
      name='password'
      type='password'
      value={password}
      onChange={(e) => setPassword(e.target.value)}
    />
  </label>
  <button type='submit'>Sign in</button>
</form>
  );
}

这也是我的 github 整个代码的回购协议; GitHub Repo

更新:第一次登录时,用户信息显示在终端上,但在我刷新页面后,它显示 undefined

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

const options = {
  providers: [
     
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        console.log(credentials);
        let user;

        const res = await fetch('http://localhost:3000/api/profile/', {
          method: 'POST',
          body: JSON.stringify(credentials),
          headers: {
            'Content-Type': 'application/json',
          },
        });
        const arrayToJson = await res.json();
        user = arrayToJson[0];

        if (user) {
          return user;
        } else {
          return null;
        }
      },
    }),
  ],
  pages: {
    signIn: '/signin',
  },
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,
    updateAge: 24 * 60 * 60,
  },
  callbacks: {
    async signIn(user) {
      return user.userId && user.isActive === '1';
    },
    async session(session, token) {
      session.user = token.user;
      return session;
    },
    async jwt(token, user) {
      if (user) token.user = user;
      return token;
    },
  },

  database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
};

export default (req, res) => NextAuth(req, res, options);

所以问题出在代码的 callbacks 部分。现在工作正常