【问题标题】:NextAuth authorizes user but user info is nullNextAuth 授权用户,但用户信息为空
【发布时间】:2021-08-26 07:48:54
【问题描述】:

我正在尝试使用凭据(电子邮件和密码)实现 NextAuth。
我已经为此设置了我的 mongodb。我还设置了/api/proile/ 路由来发布登录凭据并使用 Postman 进行测试,正确返回用户。


但是问题从登录后开始。当我登录时,凭据在 vscode 终端中返回(我使用 console.log(credentials) 控制台登录 /api/auth/[...nextauth].js 但在浏览器中它授权用户,我可以访问并查看受保护的路线和东西,但是当我在前端记录会话时,它显示为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);

顺便说一句,当我像我在上面的代码中评论的那样使用静态用户凭据时,它可以正常工作并正确返回会话信息...

还有我的/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

【问题讨论】:

    标签: node.js reactjs authentication next.js next-auth


    【解决方案1】:
    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 部分。现在它工作正常

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 2017-12-25
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2022-10-20
      • 1970-01-01
      相关资源
      最近更新 更多