Search code examples
google-apigoogle-oauthaccess-token

Using Google API in Node.js : Avoiding repetitive authorization


I am trying to build an API that requires to view my Google Calendar every time a request comes in (not the calendar of the user sending in the request). My API should be able to respond to requests of users without asking me to authenticate again and again. This API is hosted on Heroku currently.

I am following the Quickstart project for this purpose. The access token is stored in token.json file in this project. I dont understand how this project deals with expiry of the access token. I can't identify the point where the access token is refreshed and rewritten to token.json in this Quickstart project. We are only writing to the token.json file when we first create it and never after this. How will the access token be refreshed on expiry in this project?

I am also unable to figure out where I should store the token.json file. I have tried to manually authorize the API and then store the token obtained as an environment variable on heroku. It was working fine yesterday but is giving The API returned an error: Error: unauthorized_client today, by which I assume my token has expired. How can I make sure that the API doesn't require repetitive authorization from my side every time a user sends in an HTTP request to the API?


Solution

  • You can create a service account and generate a service-key.json file via google cloud IAM & Admin: screenshot of where IAM & Admin can be found

    Then, in your code, you can authorize using the service account:

    import {google} from 'googleapis';
    
    const initAuth = async () => {
      const auth = new google.auth.GoogleAuth({
        keyFile: './service-key.json', //path to service-key.json
        scopes: ['https://www.googleapis.com/auth/drive'], //any auth scopes
      });
    
      const authClient = await auth.getClient();
      google.options({auth: authClient});
    };