从 next_auth 获取 access_token 以与 googleapis 一起使用

get access_token from next_auth to use it with googleapis

如何从 next_auth 获取 access_token 以将其与 googleapi 一起使用,

假设我正在创建一个将数据存储在 google 驱动器中的 crud 应用程序,我正在使用 nextjs 和 next-auth 实现 google 的 OAuth。我发现了这个 blog 所以我实现了它。但它记录未定义。

src/pages/api/auth/[...nextauth].ts

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import jwt from 'next-auth/jwt'
const secret = process.env.SECRET

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorization:{
        params:{
          scope:"openid https://www.googleapis.com/auth/drive.file"
        }
      }
    }),
  ],
  secret: process.env.SECRET,
  callbacks: {
    jwt: ({token, user, account, profile, isNewUser})=> {
      console.log({token,user,account,profile})
      if (account?.accessToken) {
        token.accessToken = account.accessToken;
      }
      return token;
    },
    session: async ({session, user,token}) => {
      session.user = user;
      session.token = token;
      return session
    }
  },
});

我用 nextjs 创建了一个路由来获取访问令牌

import {getToken,decode} from 'next-auth/jwt'

const handler = async(req, res)=> {
    const secret = process.env.SECRET
    const token = await getToken({ req, secret });
    const accessToken = token.accessToken;
    console.log(accessToken)
}
export default handler

任何帮助都会很棒。谢谢

documentation 中所述,您 必须 转发您希望在令牌中可用的任何数据,例如您的 accessToken 值:

The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token through the jwt() callback, you have to explicitly forward it here to make it available to the client.

因此,您只需将此添加到您的 session 回调中:

  session.accessToken = token.accessToken;

google 的令牌存储在 account.access_token 而不是 account.accessToken。所以jwt回调必须是

callbacks: {
    jwt: ({token, account })=> {
      if (account?.access_token) {
        token.access_token = account.access_token;
      }
      return token;
    },
  },

并且最好不要在客户端公开令牌,这是我在会话回调中所做的。这是不安全的。