Search code examples
oauthnext.jsgoogle-drive-apinext-auth

get access_token from next_auth to use it with googleapis


How to get access_token from next_auth to use it with googleapis,

lets say i am creating a crud app that store the data in google drive, I am using nextjs and next-auth for OAuth implementation for google. i found this blog so i implemented it. but it logs undefined.

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
    }
  },
});

and I created a route with nextjs to get the access token

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

any help would be great. thanks


Solution

  • the google's token is stored in account.access_token not account.accessToken. so the jwt callback must be

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

    and it is better not to expose tokens on clients side which I done in session callback. it is insecure.