Authenticate Google OAuth with a custom backend using a unique access token and refresh token

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 issue at hand is that next-auth generates its own tokens. However, I wish to instruct next-auth to utilize the access and refresh tokens from my NestJS backend instead. How can this be achieved?

Additionally, in NestJS I've implemented an API for refreshing the access token as shown below:

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

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

Answer №1

In my opinion, the best approach would be to store the previous timestamp in local storage and then compare it with the current timestamp before calling the API. Utilizing moment.unix() or moment.diff() functions can help achieve this efficiently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Heroku does not support the installation of the @parcel/transformer-sass package

Currently, my package bundler is Parcel and the complete app is hosted on Heroku. The architecture of the app consists of two main folders - one for the client side and the other for the server side. For styling purposes on the client side, I'm utiliz ...

Experiencing issues with Panolens.js failing to load images

Currently, I am in the process of setting up a basic 3D image viewer using Panolens.js. Despite following the example provided in the documentation, I am encountering console errors during the loading process. This is my initial attempt at working with equ ...

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...

Comparing npm install --save versus npm install --save-dev

Hey everyone, I've been using npm install -g to globally install node modules/packages, but I'm a bit confused about the --save and --save-dev options. I tried looking it up on Google, but I'm still not entirely sure. Can you guys help clar ...

Adding an item to a sleek carousel

Adding items to a Slick carousel in a vue.js demo is proving to be a bit tricky. When I try to use the refresh() function after adding an item, it doesn't seem to work as expected even though the item is successfully added with vue.js. //Attempting to ...

Implement a vertical bar to appear next to the tree view when it is expanded

I am struggling to implement a vertical line for the first level of list items when they are expanded and remove it when they are closed. I have tried using li::after but it doesn't seem to work. Can someone provide guidance on how to achieve this? T ...

Verify the dialog box return with a text input box

I am trying to implement a confirmation dialog box for when a user wants to delete their account. This dialog box requires the user to enter their password in a textbox. However, I am struggling with catching the postback event and executing the relevant m ...

Extracting data from a secured internal website using web scraping and JavaScript notifications

Recently, I have been attempting to extract raw XML data from an internal company website (the URL has been omitted for security reasons). To achieve this, I am currently utilizing selenium and beautifulsoup, but I am open to exploring alternative options. ...

Initiating external libraries at the right time in Angular 4

I am currently experimenting with a UI kit (you can check it out here) that comes with multiple JavaScript files, jQuery, Bootstrap, and its own components. I have included them in my index.html file and everything works perfectly as long as the checkbox ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

Tips for emphasizing a searched item in V-data-table using VueJS

Is it possible to highlight a specific value in a v-data-table by searching for a particular word? Below is a snippet of my current code: EDIT: I am using the CRUD-Actions Example from the official Vuetify documentation. https://vuetifyjs.com/en/componen ...

Error: The function authClient.request is not recognized in Node.js with googleapis

I am currently utilizing googleapis and google auth for managing events on Google Calendar. While I was able to successfully fetch the calendar event list, encountering an error when attempting to insert a new event. The error message being thrown is: Type ...

What is the best method for sending information to a Fauna Create function?

Currently, I am in the process of developing a Next.js website and have made the decision to utilize Fauna as the database for my project. When it comes to the front-end, I am sending an object to the back-end API using the following code: async functio ...

jQuery eliminates initial div just a single time

Here is a function I have created: function removeDiv() { var topmost = jQuery('.xx'); var totContent = topmost.find('.zz').length; var $target = jQuery('.xx').find('.zz').eq(0); if(totCont ...

I am on a quest to locate a specific key within an array of objects and then validate it using Regex

I've been struggling with this for over 3 days and still haven't found a solution. It feels like trying to find a needle in a haystack, but I'm determined to figure it out. My goal is to search for a specific key in an array of objects and ...

Angular.js fails to load successfully every other time

My angular application is running into some issues with bower. At times, when I start up the server, I encounter the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:modulerr] Failed to in ...

Ensure both mouse clicks and pressing the enter key are functional for improved accessibility

Consider the following form with a tabindex property: <form id="settings-form"> <input type="text" /> <input type="submit" /> <a href="#" class="cancel-save" tabindex="0">cancel</a> </form> An action is bou ...

The jQuery method .find() is unable to locate the <option> tag and behavior unpredictably

Currently, I am working on a webpage that features a table with filtering capabilities using jQuery. The filtering functionality is achieved through a Bootstrap 4 dropdown menu where each option is assigned a specific value: <select id="inputState& ...

Jest test encountering an issue where FileReader, File, and TextDecoder are not defined

While I have primarily used Jasmine for tests in the past, I am now experimenting with Jest. However, I have encountered an issue where classes like FileReader, File, and TextDecoder are not defined in my tests. How can I incorporate these classes with t ...