简体   繁体   English

如何在不下载Google Cloud Java SDK的情况下对服务帐户进行身份验证(不在App Engine上)

[英]How to authenticate a service account without download for the Google Cloud Java SDK (not on App Engine)

I am trying to create a service account key programmatically in Java with the Google Cloud SDK, for an application not running on App/Compute engine. 我正在尝试使用Java和Google Cloud SDK以编程方式为未在App / Compute引擎上运行的应用程序创建服务帐户密钥。 This question is similar to mine, but it is running on App engine, so I cannot use the same code as it uses classes from the App Engine API. 这个问题类似于我的问题,但是它在App Engine上运行,因此我无法使用与使用App Engine API中的类相同的代码。

The relevant code is below. 相关代码如下。 My issue is that AppIdentityCredential is part of the AppEngine API and thus cannot be used here. 我的问题是AppIdentityCredential是AppEngine API的一部分,因此不能在此处使用。 What can I pass in as a parameter instead? 我可以将什么作为参数传递呢? The third parameter in the new Builder() method takes in an HttpRequestInitializer , but I don't understand what implementation of this interface I should pass in. Any help is appreciated. 新的Builder()方法中的第三个参数采用HttpRequestInitializer ,但是我不知道我应该传递该接口的哪种实现。我们将提供任何帮助。

import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;

AppIdentityCredential credential = new AppIdentityCredential(
            Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,credential)
         .setApplicationName(APPLICATION_NAME).build();
ServiceAccountKey key = iam.projects().serviceAccounts().keys()
     .create(SERVICE_ACCOUNT_RESOURCE_NAME, new CreateServiceAccountKeyRequest()).execute();

You can use Application Default Credentials which will allow you to use the same code to fetch the credentials based on the environment where the application is running. 您可以使用“ 应用程序默认凭据” ,它允许您根据应用程序运行的环境使用相同的代码来获取凭据。

For example, it lets you use your gcloud account credentials when you're developing on your system. 例如,它允许您在系统上进行开发时使用gcloud帐户凭据 When the code runs on Google Compute Engine or Google App Engine, the code will automatically use the associated service account credentials for authentication in the APIs. 当代码在Google Compute Engine或Google App Engine上运行时,代码将自动使用关联的服务帐户凭据在API中进行身份验证。 You can also override it using GOOGLE_APPLICATION_CREDENTIALS environment variable if required to load the credentials from a JSON file instead. 如果需要从JSON文件加载凭据,也可以使用GOOGLE_APPLICATION_CREDENTIALS环境变量覆盖它。

Here is a working example which creates a new key for an existing service account and prints it. 这是一个工作示例,该示例为现有服务帐户创建一个新密钥并进行打印。

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

public class IamDemo {
  /** Name of the application. */
  private static final String APPLICATION_NAME = "IamDemoJava";

  /** Project Name. */
  private static final String PROJECT_NAME = "MY_PROJECT_NAME";

  /** Name of the service account to create a new key for. */
  private static final String SERVICE_ACCOUNT_NAME = "dummy-sa";

  /** Full email address of the service account. */
  private static final String SERVICE_ACCOUNT_EMAIL =
      SERVICE_ACCOUNT_NAME + "@" + PROJECT_NAME + ".iam.gserviceaccount.com";

  /** Full service account resource string expected by the IAM API. */
  private static final String SERVICE_ACCOUNT_RESOURCE_NAME =
      "projects/" + PROJECT_NAME + "/serviceAccounts/" + SERVICE_ACCOUNT_EMAIL;

  /** Global instance of the HTTP transport. */
  private static HttpTransport httpTransport;

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

  public static void main() throws IOException, GeneralSecurityException {
    Iam iam = initIam();
    ServiceAccountKey key = createServiceAccountKey(iam);

    // Print the key
    System.out.println(key.toString());
  }

  private static Iam initIam() throws IOException, GeneralSecurityException {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    // Authenticate using Google Application Default Credentials.
    GoogleCredential credential = GoogleCredential.getApplicationDefault();


    if (credential.createScopedRequired()) {
      List<String> scopes = new ArrayList<>();
      // Enable full Cloud Platform scope.
      scopes.add(IamScopes.CLOUD_PLATFORM);
      credential = credential.createScoped(scopes);
    }

    // Create IAM API object associated with the authenticated transport.
    return new Iam.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME)
        .build();
  }

  private static ServiceAccountKey createServiceAccountKey(Iam iam)
      throws IOException, GeneralSecurityException {
    CreateServiceAccountKeyRequest request = new CreateServiceAccountKeyRequest();

    // Customize the request parameters if needed

    return iam.projects()
        .serviceAccounts()
        .keys()
        .create(SERVICE_ACCOUNT_RESOURCE_NAME, request)
        .execute();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用服务帐户向Google Cloud SQL Java进行身份验证 - How to use Service Account to authenticate with Google Cloud SQL Java 如何使用服务帐户验证com.google.cloud.bigquery.BigQuery` - how to authenticate `com.google.cloud.bigquery.BigQuery` with service account 无法验证服务帐号 - Google Cloud - Unable to authenticate service account - Google Cloud 如何在Google App Engine上进行身份验证 - How to Authenticate at Google App Engine 我们如何使用适用于Eclipse的新Google Cloud Plugin更新App Engine Java SDK? - How can we update the App Engine Java SDK Using the New Google Cloud Plugin for Eclipse? 没有应用引擎,如何连接Google Cloud实例 - How could i connect with Google cloud instance without app engine 适用于Java和Google云存储的Google App Engine - Google App Engine for Java and Google Cloud Storage 通过Cloud Endpoints V2下载App Engine SDK - App Engine SDK Download with Cloud Endpoints V2 如何使用 Google Cloud 中的 Google 服务帐户登录? - How to log in with a Google Service account in the Google Cloud? 如果您安装了Eclipse的Google插件,是否还需要下载App Engine Java SDK? - If you install the Google Plugin for Eclipse, do you still need to download the App Engine Java SDK?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM