next.js 正在查找指针以解决“无法读取未定义的属性(阅读”jwt“)”问题

pvabu6sv  于 2023-02-12  发布在  其他
关注(0)|答案(1)|浏览(144)

我的身份验证流程遇到了问题,希望有眼光敏锐的人可以帮助我解决这个问题。我得到的错误是[next-auth][error][JWT_SESSION_ERROR] https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'jwt'),我已经多次检查代码,看看哪里可能出了问题。下面是我采取的步骤,以及您如何能够重现错误:
1.如下所示设置和配置[...nextauth].js file
1.已使用所需凭据更新提供程序。
在尝试登录进行测试时,我收到了如下所示的错误消息。
frontend/pages/api/auth/[...nextauth].js

import NextAuth from "next-auth";
import GoogleProvider from 'next-auth/providers/google';
import FacebookProvider from 'next-auth/providers/facebook';
import EmailProvider from 'next-auth/providers/email';

const options = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
  ],
  pages: {
    signIn: '/signin',
    signOut: '/',
    error: '/auth/error', // Error code passed in query string as ?error=
    verifyRequest: '/auth/verify-request', // (used for check email message)
    newUser: '/firstpage', // New users will be directed here on first sign in (leave the property out if not of interest)
  },
  secret: process.env.NEXTAUTH_SECRET,
  database: process.env.NEXT_PUBLIC_DATABASE_URL,
  session: {
    jwt: true,
  },
  callbacks: {
    session: async (session, user) => {
      session.jwt = user.jwt;
      session.id = user.id;
      return Promise.resolve(session);
    },
    jwt: async (token, user, account) => {
      const isSignIn = user ? true : false;
      if (isSignIn) {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_STRAPI_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}`
        );
        const data = await response.json();
        console.log("DATTA",data);
        token.jwt = data.jwt;
        token.id = data.user.id;
      }
      return Promise.resolve(token);
    },
  },
};

const Auth = (req, res) =>
  NextAuth(req, res, options);

export default Auth;

Error below

[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'jwt') {
  message: "Cannot read properties of undefined (reading 'jwt')",
  stack: "TypeError: Cannot read properties of undefined (reading 'jwt')\n" +
    '    at Object.session (webpack-internal:///(api)/./pages/api/auth/[...nextauth].js:45:32)\n' +
    '    at Object.session (/Users/PATH-TO-FILES...)\n'

  name: 'TypeError'
}
oug3syen

oug3syen1#

尝试将jwt回调中的URI替换为:const response = await fetch(${process.env.NEXT_PUBLIC_API_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token});
下面是我对[...nextauth].js的配置。注意:我使用authOptions而不是options,以便能够在getServerSideProps中的服务器上获得会话。

import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import axios from 'axios';

const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    CredentialsProvider({
      name: 'Email',
      type: 'credentials',

      async authorize(credentials) {
        const { email, password } = credentials;

        try {
          const { data } = await axios.post(
            `${process.env.NEXT_PUBLIC_API_URL}/api/auth/local`,
            {
              identifier: email,
              password: password,
            }
          );
          const user = await data;

          if (user) {
            return user;
          } else {
            return null;
          }
        } catch (err) {
          return null;
        }
      },
    }),
  ],

  session: {
    jwt: true,
  },
  secret: process.env.NEXTAUTH_SECRET,

  callbacks: {
    async session({ session, token, user }) {
      session.jwt = token.jwt;
      session.id = token.id;
      return session;
    },
    async jwt({ token, user, account }) {
      if (user) {
        if (account.provider !== 'credentials') {
          const response = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
          );
          const data = await response.json();

          token.jwt = data.jwt;
          token.id = data.user.id;
        } else {
          token.jwt = user.jwt;
          token.id = user.user.id;
        }
      }

      return token;
    },
  },

  pages: {
    signIn: '/auth/signin',
  },
};

const Auth = (req, res) => NextAuth(req, res, authOptions);

export default Auth;```

相关问题