5

I have a NestJS backend that exposes the following API:

   @Post('sign-in-with-google-account')
   async signInWithGoogleAccount(
     @Body body: { idToken: string }, 
     @Res({ passthrough: true }) response: Response
   ) {
     const user = await getUserFromGoogleIdToken(body.idToken)
     const tokens = await generateAccessAndRefreshTokensForUser(user)

     response.cookie('refreshToken', tokens.refreshToken, {
         httpOnly: true,
         expires: new Date(tokenExpirationDate),
         secure: true,
         sameSite: 'none'
     })

     return { accessToken: tokens.accessToken }
   }

It receives id token from google oauth, finds the user in the DB and signs a JWT access token and refresh token. The refresh token is stored as httpOnly cookie and the access token is returned.

Now in my next.js app configured with next-auth I have the following:

import GoogleProvider from "next-auth/providers/google";

...
providers: [
  GoogleProvider({
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET
  })
]
...

The problem is that next-auth generates its own tokens. But I want next-auth to use my own access and refresh tokens from the NestJS backend, how can I do that?

Also, In NestJS I have a API to refresh the access token like so:

@Get('refresh-access-token')
async refreshAccessToken(@Req() request: Request) {
  const accessToken = await getNewAccessTokenFromRefreshToken(request.cookies.refreshToken)
  return { accessToken } 
}

How can I tell next-auth to refresh the access token using refresh-access-token API every 10 minutes (the access token expiration date)?

Two Horses
  • 1,401
  • 3
  • 14
  • 35
  • 1
    Have you got the answer for this question? I'm also stuck in same scenario. I want to use the `next-auth` to use the tokens generated by my custom backend. Not the one created by next-auth itself. I want to integrate `Google Login` and `Credentials Provider` – Osama Ehsan Jul 27 '23 at 09:24
  • 2
    Unfortunately no. There is 0 documentation about this. I guess next-auth and next.js in general is more about doing NOTHING custom, but to pay for third party services like auth0 or clerk. I gave up on next.js and decided to use good old react + vite – Two Horses Jul 27 '23 at 10:55
  • Looking into this question might help: https://stackoverflow.com/questions/359472/how-can-i-verify-a-google-authentication-api-access-token – Abhik Banerjee Aug 15 '23 at 18:37

1 Answers1

0

I think you need to save the previous time to local storage and then compare it with current time to call the api. You can use moment.unix() or moment.diff() to do this.

katorianh
  • 26
  • 1
  • 4