Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过服务访问密钥以编程方式对Google计算引擎进行身份验证_Java_Google Compute Engine - Fatal编程技术网

Java 通过服务访问密钥以编程方式对Google计算引擎进行身份验证

Java 通过服务访问密钥以编程方式对Google计算引擎进行身份验证,java,google-compute-engine,Java,Google Compute Engine,在研究Google Compute文档之后,我发现没有通过生成的服务访问密钥进行身份验证的例子 我用以下代码进行了尝试(这是第69行) 及 client_secrets.json是从google生成的文件,如下所示 { "type": "service_account", "project_id": "...", "private_key_id": "...", "private_key": "-----BEGIN PRIVATE KEY-----...-----END PRIVATE

在研究Google Compute文档之后,我发现没有通过生成的服务访问密钥进行身份验证的例子

我用以下代码进行了尝试(这是第69行)

client_secrets.json是从google生成的文件,如下所示

{
 "type": "service_account",
 "project_id": "...",
 "private_key_id": "...",
 "private_key": "-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----\n",
 "client_email": "....iam.gserviceaccount.com",
 "client_id": "...",
 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
 "token_uri": "https://accounts.google.com/o/oauth2/token",
 "auth_provider_x509_cert_url": 
 "https://www.googleapis.com/oauth2/v1/certs",
 "client_x509_cert_url": 
 "https://www.googleapis.com/robot/v1/metadata/x509/..."
}
执行此代码时,我收到的所有信息是

java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.setClientSecrets(GoogleCredential.java:559)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GCEImporter.getAssets(GCEImporter.java:69)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GoogleImporterTest.getAssets(GoogleImporterTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

有人能解决这个问题吗?

这里有几个问题:

  • 从IAM页面创建新服务帐户时下载的私钥信息json文件不在中

  • 您正在尝试遵循适用于桌面和移动应用程序的
    [OAuth步骤][2]
    。这不适用于谷歌云API

使用Google Cloud API进行授权的推荐且更简单的方法是使用应用程序默认凭据,如下所述

简而言之,你需要做的是(根据大纲):

  • 在环境变量
    GOOGLE\u APPLICATION\u CREDENTIALS
    中设置JSON文件的路径

  • 创建
    GoogleCredential
    对象,如下所示

  • GoogleCredential-credential=GoogleCredential.getApplicationDefault()

    完成上述步骤后,您应该能够与任何Google Cloud API进行对话。对于GCE,您将创建
    Compute

    Compute=new Compute.Builder
    (传输,jsonFactory,凭证).build()

    我只是从compute.instances.insert API复制和粘贴示例


    谢谢你的回答。 我也尝试了你的方式,通过复制网站上的例子提前。但这只在GCE环境中的实例中起作用

    我自己找到了一个解决方案,它是来自GoogleCredential类的静态方法:

    GoogleCredential.fromStream(new FileInputStreamReader("path/to/json"))
    
    java.lang.IllegalArgumentException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
    at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
    at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.setClientSecrets(GoogleCredential.java:559)
    at net.bytesource.jira.asset.synchronization.importer.google.gce.GCEImporter.getAssets(GCEImporter.java:69)
    at net.bytesource.jira.asset.synchronization.importer.google.gce.GoogleImporterTest.getAssets(GoogleImporterTest.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    
    /*
     * BEFORE RUNNING:
     * ---------------
     * 1. If not already done, enable the Compute Engine API
     *    and check the quota for your project at
     *    https://console.developers.google.com/apis/api/compute
     * 2. This sample uses Application Default Credentials for authentication.
     *    If not already done, install the gcloud CLI from
     *    https://cloud.google.com/sdk and run
     *    `gcloud beta auth application-default login`.
     *    For more information, see
     *    https://developers.google.com/identity/protocols/application-default-credentials
     * 3. Install the Java client library on Maven or Gradle. Check installation
     *    instructions at https://github.com/google/google-api-java-client.
     *    On other build systems, you can add the jar files to your project from
     *    https://developers.google.com/resources/api-libraries/download/compute/v1/java
     */
    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.compute.Compute;
    import com.google.api.services.compute.model.Instance;
    import com.google.api.services.compute.model.Operation;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
    
    public class ComputeExample {
      public static void main(String args[]) throws IOException, GeneralSecurityException {
        // Project ID for this request.
        String project = ""; // TODO: Update placeholder value.
    
        // The name of the zone for this request.
        String zone = ""; // TODO: Update placeholder value.
    
        // TODO: Assign values to desired fields of `requestBody`:
        Instance requestBody = new Instance();
    
        Compute computeService = createComputeService();
        Compute.Instances.Insert request =
            computeService.instances().insert(project, zone, requestBody);
    
        Operation response = request.execute();
    
        // TODO: Change code below to process the `response` object:
        System.out.println(response);
      }
    
      public static Compute createComputeService() throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
        GoogleCredential credential = GoogleCredential.getApplicationDefault();
        if (credential.createScopedRequired()) {
          credential =
              credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
        }
    
        return new Compute.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("Google-ComputeSample/0.1")
            .build();
      }
    }
    
    GoogleCredential.fromStream(new FileInputStreamReader("path/to/json"))