I am trying to implement the Google Drive API, for back-end use only. Users will not be logging into this site. I simply want to get an access token to my own Drive account from the server, without needing to constantly log in. This is for background process use only, and users will never actually interact with it.
I've enabled the Drive API and created app service credentials for it, and I have the secret.json
file for authenticating. However, Google's documentation seems to only briefly mention userless server-side authentication a few times and then glazes over it. I can't find ANY official documentation on how to authenticate this way.
I was following the official node.js example but it still requires you to open a page to authenticate. Is this what I need? Does the token granted from this ever expire?
In your situation, I think that OAuth2 is used. By this, when the refresh token and access token are retrieved, it is required to authorize the scopes by the browser. This is the current specification at Google side. In this case, the expiration times of the access token and refresh token are 1 hour and six months, respectively. Ref
When you want to use Drive API without using the browser, as a workaround, how about using the service account instead of OAuth2? Although the access token retrieved by the service account has 1 hour in the expiration time, when the service account is used, the Drive API can be used without opening the page for retrieving the authorization code with the browser.
The sample script of googleapis for Node.js for using the service account is as follows.
In this sample script, the file list of the Google Drive of the service account is retrieved. serviceAccount.json
is the file including JSON object retrieved by creating the service account.
const { google } = require("googleapis");
const key = require("./serviceAccount.json");
const client = new google.auth.JWT(
key.client_email,
null,
key.private_key,
["https://www.googleapis.com/auth/drive.readonly"],
null
);
client.authorize((err) => {
if (err) {
console.log(err);
}
});
drive = google.drive({ version: "v3", auth: client });
drive.files.list(null, (err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.data);
});