【问题标题】:Creating a file in Google Drive (G Suite) from Java with Service Account: 403 Insufficient Permission使用服务帐户从 Java 在 Google Drive (G Suite) 中创建文件:403 Insufficient Permission
【发布时间】:2020-10-04 20:35:40
【问题描述】:

我正在尝试在 Google Drive 文件夹中创建一个文件。

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

我与生成的服务帐户电子邮件共享了我的 G Suite 云端硬盘文件夹,并授予它编辑者访问权限(读取、写入、编辑)。

我试图从我的 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注解的谷歌驱动服务工作正常。创建如下:

@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 文件夹中写入什么有任何想法吗?

【问题讨论】:

  • 是否为项目和服务帐号启用了 Drive API?
  • @Aerials 是的!我可以轻松阅读。

标签: java spring-boot google-drive-api google-workspace


【解决方案1】:

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

GoogleCredential.fromStream(source).createScoped(scopes)

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

【讨论】:

  • 是的,没错。我分配了两次范围。第二次只用read 权限替换它们。
猜你喜欢
  • 1970-01-01
  • 2013-10-15
  • 2016-09-04
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2020-04-05
相关资源
最近更新 更多