Next Auth google OAuth with custom backend's access token and refresh token
Asked Answered
W

1

6

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)?

Waverly answered 27/1, 2023 at 12:45 Comment(4)
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 ProviderEusporangiate
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 + viteWaverly
Looking into this question might help: #359972Ramsden
did u find any solution to this question im stuck too in this senario?Transcendentalistic
E
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.

Edy answered 27/1, 2023 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.