NextAuth回调未运行

bqjvbblv  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(389)

我正在用Next.js设计一个应用程序,并使用NextAuth进行身份验证(使用Google OAuth)。为了在验证后使用其他Google API,我希望持久化accessToken。accessToken在session()回调中设置。但是,回调似乎永远不会运行。有人能帮我一下吗?谢谢!
这是我的[... nextauth].js文件

import GoogleProvider from "next-auth/providers/google"
import NextAuth from "next-auth/next"
export default NextAuth(
  {
    // Configure one or more authentication providers
    providers: [
      GoogleProvider({
        clientId: PROCESS.ENV.GOOGLE_CLIENT_ID',
        clientSecret: PROCESS.ENV.GOOGLE_CLIENT_SECRET,
        authorization: {
          params: {
            prompt: "consent",
            access_type: "offline",
            response_type: "code",
            scope: 'openid email profile https://www.googleapis.com/auth/calendar'
          },
        },
        callbacks: {
          async session({ session, token, user }) {
            session.user.id = token.id;
            session.accessToken = token.accessToken;
            // Not printed
            console.log('In here');
            return session;
          },
          async jwt({ token, user, account, profile, isNewUser }) {
            console.log(token);
            if (user) {
              token.id = user.id;
            }
            if (account) {
              token.accessToken = account?.access_token;
            }
            return token;
          },
        },
      }),
      // ...add more providers here
    ],
    sercet: PROCESS.ENV.JWT_SECRET,
    session: {
      strategy: "jwt",
    },
  }
)

下面是我的登录组件:

import React, { useState } from 'react';
import {useSession, signIn, signOut} from 'next-auth/react';
import axios from 'axios';

const Login = () => {
    const x = useSession();
    const {data: session} = x
    const [calendar, setCalendar] = useState({});

    const getCalendarData = async () => {
        console.log(session.accessToken);
        console.log(x);
        const options = {  
            method: 'GET',
            headers: {
                Authorization: `Bearer ${session.accessToken}`,
            }
        };

        const url = "https://www.googleapis.com/calendar/v3/calendars/primary";
        
        const data = null
        try{
            data = await axios.get(url, options);
            setCalendar(data);
        } catch(error){
            console.log(error);
        }
        
    }

    if(session){
        return (
            <div>
                <div> Welcome, {JSON.stringify(session.user)} </div>
                <div>{JSON.stringify(calendar)}</div>
                <div><button onClick={() => signOut()}>Sign Out</button></div>
                <div><button onClick={async () => await getCalendarData()}>Get Calendar Data</button></div>
            </div>
        
        );
    }
    else{

        return(
            <div>
                <div> You are not signed in </div>
                <div><button onClick={() =>signIn()}> Sign in</button></div>
            </div>
            )
    }
}
vfhzx4xs

vfhzx4xs1#

如果问题还没有解决,我有一个建议。我写这篇文章是因为我在互联网上找不到解决方案。希望能有所帮助:错误可能与MongoDB或您正在使用的数据库有关。在MongoDB中,转到您创建的数据库并单击“添加当前IP地址”。然后关闭并重新打开Next.js项目。这应该可以解决问题。MongoDB将最后添加的IP地址保存为可信地址。因此,当您的IP地址更改时,它不允许访问服务器,您需要将当前IP地址添加到数据库中。

相关问题