从 Java 使用服务帐户在 Google Drive (G Suite) 中创建文件:403 权限不足

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

我正在尝试在 Google 驱动器文件夹中创建一个文件。

从文件夹读取有效。我已经在使用不同服务帐户的不同应用程序中读取文件。

我与生成的服务帐户电子邮件共享了我的 G Suite Drive 文件夹并授予其编辑权限(读、写、编辑)。

我试图从我的 Java Springboot 应用程序复制一个现有文件(但也从头开始创建一个空文件)。

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();
    }
}

注入了 @Autowired 注释的 google 驱动服务工作正常。创建如下:

@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();
    }

    ...
}

关于服务帐户需要能够在 G Suite Drive 文件夹上写入的内容有什么想法吗?

您必须授予 GoogleCredentials 对象所需的权限,即

GoogleCredential.fromStream(source).createScoped(scopes)

范围可以在例如SheetsScopes 或 DriveScopes(取决于您的 Google 依赖项)