Access Google Drive without OAuth2
Google API's indeed work only via OAuth2.0 using a bearer
token.
But you can obtain a bearer
token from a GCP Service Account's JWT token. Since OAuth via JWT is automatic, no user interaction is involved.
Just create a Service Account, generate a key in JSON format, and "share" your Drive folder with that service account ([email protected]
).
Note: a Service Account's key file looks like this (redacted):
{
"type": "service_account",
"project_id": "<skip>",
"private_key_id": "<skip>",
"private_key": "-----BEGIN PRIVATE KEY-----\n <skip> \n-----END PRIVATE KEY-----\n",
"client_email": "<skip>@<skip>.iam.gserviceaccount.com",
"client_id": "<skip>",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/<skip>%40<skip>.iam.gserviceaccount.com"
}
Example of listing files in Go:
package main
import (
"fmt"
"log"
"golang.org/x/net/context"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
func main() {
srv, err := drive.NewService(context.Background(), option.WithCredentialsFile("key.json"))
if err != nil {
log.Fatal("Unable to access Drive API:", err)
}
r, err := srv.Files.List().PageSize(100).Fields("nextPageToken, files").Do()
if err != nil {
log.Fatal("Unable to list files:", err)
}
fmt.Println("Files:")
for _, i := range r.Files {
fmt.Printf("%v (%v) %v %v\n", i.Name, i.Id, i.MimeType, i.Parents)
}
}
Output:
Files:
Test (1TMx<skip>SoYJ5) application/vnd.google-apps.folder []
Test.txt (1Ele<skip>Fh98n) text/plain [1TMx<skip>SoYJ5]
Test2.txt (3ce9x<skip>lsWds) text/plain [1TMx<skip>SoYJ5]