用于Java的OAuth Google API无法模拟用户


问题内容

我想模拟一个用户,并代表他们从服务器进程向用户Google
Drive添加文件。我已经设置了服务帐户,并且可以使用以下代码作为添加和列出文件的服务帐户成功访问云端硬盘:

  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  public static void main(String[] args) {
    try {
        GoogleCredential credential = 
                new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setServiceAccountId("XXXXX@developer.gserviceaccount.com")
                  .setServiceAccountScopes(DriveScopes.DRIVE)
                  .setServiceAccountPrivateKeyFromP12File(new File("c:/junk/key.p12"))
                  .build();
        Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();         
        drive.files().list().execute();
  } catch (Exception e) {
     e.printStackTrace();
  }

这可行,但是仅返回与我认为与服务帐户驱动器(?)相关联的文件。

根据JavaDoc,通过添加服务帐户用户的电子邮件地址,还可以使用GoogleCredential来模拟用户:

        GoogleCredential credential = 
                new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setServiceAccountId("XXXXX@developer.gserviceaccount.com")
                  .setServiceAccountScopes(DriveScopes.DRIVE)
                  .setServiceAccountPrivateKeyFromP12File(new File("c:/junk/key.p12"))
                  .setServiceAccountUser("usera@domain.com") //<-- impersonate user a
                  .build();

但是,执行此代码时,将引发以下异常:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "access_denied"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:103)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:340)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:508)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:260)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:796)
at com.google.api.client.googleapis.json.GoogleJsonResponseException.execute(GoogleJsonResponseException.java:198)
at com.google.api.client.googleapis.services.GoogleClient.executeUnparsed(GoogleClient.java:237)
at com.google.api.client.http.json.JsonHttpRequest.executeUnparsed(JsonHttpRequest.java:207)
at com.google.api.services.drive.Drive$Files$List.execute(Drive.java:1071)

我是否缺少步骤或配置设置?

谢谢大卫


问题答案:

cPanel文档有点误导,因为它涉及启用使用者密钥,然后将域添加到Manage API Client Access屏幕。这似乎对gdata
api有效,而不对新的Google Drive api有效。通过按照其他问题中的建议添加客户端ID并授予对Drive范围的访问权限,我现在可以模拟用户。