Error when i use google service account : invalid jwt

196 Views Asked by At

I have an application basically for sending documents to the drive that has a login with Google, but when sending the documents I want to use the Google service account but I receive several token errors

//first import service account key file
const serviceAccountKey = require('../../../serviceAccount.json')

//after instances client account service
const authService = new google.auth.GoogleAuth({
    credentials: serviceAccountKey,
    scopes: ['https://www.googleapis.com/auth/drive']
})

const googleAccountService =  google.drive({
    version: 'v3',
    auth: authService
})

//and then

    try {
        const response = googleAccountService.files.list({
            q: 'mimeType = "application/vnd.google-apps.folder"'
        })

        if (response.data) {
            return response.data
        }

    } catch (error) {
        console.log(error);
    }

//but it catch get the error

data: { error: 'invalid_grant', error_description: 'Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.' },

1

There are 1 best solutions below

1
Linda Lawton - DaImTo On

This is the proper method to use a service account.

const { google } = require("googleapis");

const credentialFilename = "credentials.json";
const scopes = ["https://www.googleapis.com/auth/drive"];

const auth = new google.auth.GoogleAuth({keyFile: credentialFilename, scopes: scopes});
const drive = google.drive({ version: "v3", auth });

It should be the path to the key file. It sounds to me like you dont have a service account key file. open it up in a text editor it should say at the top what type it is.