Google服务帐户域范围委派使用JSON密钥文件而不是p12设置服务帐户

时间:2017-01-19 17:02:38

标签: java json google-drive-api google-apps

我可以使用.p12密钥文件使用域服务授权的Google服务帐户。

我想使用JSON密钥文件而不是p12文件,但是在使用JSON密钥时我无法弄清楚如何设置服务帐户ID。

如何使用JSON密钥文件将用户设置为模拟?

正常工作:

File p12File = new File(...);
GoogleCredential.Builder b = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY).setServiceAccountId(properties.getServiceAccountId())
                  .setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                      new FileInputStream(p12File), "notasecret",
                      "privatekey", "notasecret"))
                  .setServiceAccountScopes(GOOGLE_SCOPE_LIST);
              if (properties.getServiceAccountEmail() != null) {
                b = b.setServiceAccountUser(properties.getServiceAccountEmail());
              }
              credential = b.build();

不起作用:

String jsonKeyContents = "{\n" +
            "  \"type\": \"service_account\",\n" +
            "  \"project_id\": \"sxxxxxxx0\",\n" +
            "  \"private_key_id\": \"csxxxxxxxxxxxxxxxx\",\n" +
            "  \"private_key\": \"-----BEGIN PRIVATE " +
            "KEY-----\\nMIIxxxxxxxxxxsTbwzsbw" +
            "==\\n-----END PRIVATE KEY-----\\n\",\n" +
            "  \"client_email\": \"xxxxx@xxxxxx-123456.iam.gserviceaccount.com\",\n" +
            "  \"client_id\": \"1111111111111111111\",\n" +
            "  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" +
            "  \"token_uri\": \"https://accounts.google.com/o/oauth2/token\",\n" +
            "  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" +
            "  \"client_x509_cert_url\": \"https://www.googleapis" +
            ".com/robot/v1/metadata/x509/xxxxx%40xxxxxx-xxxxx-123456.iam.gserviceaccount.com\"\n" +
            "}";
try (InputStream privateKeyInputStream = new ByteArrayInputStream(jsonKeyContents
          .getBytes("UTF-8") )) {
        credential = GoogleCredential.fromStream(privateKeyInputStream).createScoped(GOOGLE_SCOPE_LIST);
}

使用JSON密钥使用Directory API列出所有Enterprise用户时,收到错误消息:

Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
  "code" : 404,
  "errors" : [ {
    "domain" : "global",
    "message" : "Domain not found.",
    "reason" : "notFound"
  } ],
  "message" : "Domain not found."
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
...

所有问题似乎都与没有地方放置服务帐户电子邮件的事实有关。

我在这里缺少什么?是否有人有一个工作示例他们可以共享一些代码?

2 个答案:

答案 0 :(得分:9)

毕竟,我自己找到了答案。

请参阅https://github.com/google/google-api-java-client/issues/1007#issuecomment-264157989

修复它:

  1. 使用上面指定的JSON密钥创建GoogleCredential credentialFromJson。即credential = GoogleCredential.fromStream(privateKeyInputStream).createScoped(GOOGLE_SCOPE_LIST)

  2. 使用我们使用P12 的代码创建构建器,而不是从p12文件创建私钥...使用此行:.setServiceAccountPrivateKey(credentialFromJson.getServiceAccountPrivateKey())

    < / LI>

    现在它有效! \米/

答案 1 :(得分:2)

您的JSON文件必须包含所有必需的键值对

关键

{
"type": "service_account",
"project_id": "your project Id",
"private_key_id": "private key id",
"private_key": "Private key",
"client_email": "Client email ending with .iam.gserviceaccount.com",
"client_id": "client -id",
"auth_uri": "accounts.google.com/o/oauth2/auth",
"token_uri": "accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "www.googleapis.com/robot/v1/metadata/x509/?????
-170710.iam.gserviceaccount.com"
}

然后使用以下代码:

private GoogleCredential authorize1() {

    GoogleCredential credential = null;

    HttpTransport = GoogleNetHttpTransport.newTrustedTransport();

    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    try {

      InputStream jsonFileStream =
          DriveSample.class.getClassLoader().getResourceAsStream("client_secrets.json");

      GoogleCredential readJsonFile = GoogleCredential
          .fromStream(jsonFileStream, httpTransport, JSON_FACTORY).createScoped(DriveScopes.all());

      credential = new GoogleCredential.Builder().setTransport(readJsonFile.getTransport())
          .setJsonFactory(readJsonFile.getJsonFactory())
          .setServiceAccountId(readJsonFile.getServiceAccountId())
          .setServiceAccountScopes(readJsonFile.getServiceAccountScopes())
          .setServiceAccountPrivateKey(readJsonFile.getServiceAccountPrivateKey()).build();
    } catch (IOException exception) {
      exception.printStackTrace();
    }
    return credential;
}