I need to generate around 300 Google Docs files programmatically using Java. I tried implementing the Google Docs API but I keep running into permission issues. The error shows “Insufficient Permission” and “Request had insufficient authentication scopes” when trying to create documents. I think the problem might be with the scope configuration. Originally I had DOCUMENTS_READONLY scope but that didn’t work for creating files, so I changed it to DOCUMENTS scope but still getting the same 403 error. Here’s my implementation:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.docs.v1.Docs;
import com.google.api.services.docs.v1.DocsScopes;
import com.google.api.services.docs.v1.model.Document;
public class DocumentGenerator {
private static final String APP_NAME = "Document Creator Java App";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKEN_DIR = "auth_tokens";
private static final List<String> REQUIRED_SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS);
private static final String CREDS_FILE = "/client_credentials.json";
private static Credential authorize(final NetHttpTransport transport) throws IOException {
InputStream credStream = DocumentGenerator.class.getResourceAsStream(CREDS_FILE);
GoogleClientSecrets secrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credStream));
GoogleAuthorizationCodeFlow authFlow = new GoogleAuthorizationCodeFlow.Builder(
transport, JSON_FACTORY, secrets, REQUIRED_SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKEN_DIR)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(9999).build();
return new AuthorizationCodeInstalledApp(authFlow, receiver).authorize("user");
}
private static void generateDocument(Docs docsService) throws IOException {
Document newDoc = new Document().setTitle("Generated Document");
newDoc = docsService.documents().create(newDoc).execute();
System.out.println("Successfully created: " + newDoc.getTitle());
}
}
Can someone help me figure out what’s wrong with the scope configuration or authentication setup?