Creating a file in Google Drive (G Suite) from Java with Service Account: 403 Insufficient Permission

193 Views Asked by At

I'm trying to create a file in a Google Drive folder.

Reading from the folder works. I'm already reading files in different applications with different Service Accounts.

I shared my G Suite Drive folder with the generated service account email and gave it Editor access (read, write, edit).

I tried to copy an existing file (but also create an empty one from scratch) from my Java Springboot application.

public class TemplateDocumentManager {

    @Value("${printing.template.id}")
    private String baseTemplateFileId;

    @Autowired
    private Drive driveService;

    public void createNewContractFromEmptyTemplate() throws IOException {
        File templateFile = getDriveFiles().get(baseTemplateFileId).execute();

        File newFileInstance = getDriveFiles()
                .copy(baseTemplateFileId, templateFile)
                .setSupportsAllDrives(true)
                .execute();
        log.error("Id of newly created file is: {}", newFileInstance.getId());
    }

    protected Drive.Files getDriveFiles() {
        return driveService.files();
    }
}

The google drive service injected with the @Autowired annotation is working properly. It is created as follows:

@Configuration
public class DriveService {

    public static final String APPLICATION_NAME = "appname";

    @Autowired
    GoogleCredential googleCredential;

    @Bean("driveService")
    public Drive createDriveService() throws GeneralSecurityException, IOException {
        return new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), googleCredential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    ...
}

Any ideas on what the service account needs to be able to write on the G Suite Drive folder?

1

There are 1 best solutions below

1
On BEST ANSWER

You have to give the required permissions to the GoogleCredentials Object, i.e.

GoogleCredential.fromStream(source).createScoped(scopes)

Scopes could be found in e.g. SheetsScopes or DriveScopes ( depending on your Google dependencies )