简体   繁体   English

向 Google Cloud Storage API 提供凭据

[英]Providing Credentials to Google Cloud Storage API

I'm trying to put together a hello world program for testing out Google Cloud Storage.我正在尝试编写一个 hello world 程序来测试 Google Cloud Storage。 My goal is to have the simplest possible program that just uploads a hard-coded file to Cloud Storage.我的目标是拥有最简单的程序,只需将硬编码文件上传到 Cloud Storage。

I've been scouring the internet for a basic tutorial, but the closest I could find is this guide for using Cloud Storage from App Engine.我一直在互联网上搜索基本教程,但我能找到的最接近的是使用 App Engine 中的云存储的指南 I've put together this program:我把这个程序放在一起:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;

import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class Main {
    public static void main(String[] args) throws FileNotFoundException{

        FileInputStream fileInputStream = new FileInputStream("my-file.txt");

        Storage storage = StorageOptions.getDefaultInstance().getService();

        BlobInfo blobInfo =
            storage.create(
                BlobInfo
                    .newBuilder("my-cloud-storage-bucket", "my-file.txt")
                    .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                    .build(),
                fileInputStream);

        String fileUrl = blobInfo.getMediaLink();

        System.out.println("Uploaded URL: " + fileUrl);
    }
}

When I run that code, I get a 401 Unauthorized error when I call storage.create() , and that's not surprising because I'm not providing a username or password.当我运行该代码时,我在调用storage.create()时收到401 Unauthorized错误,这并不奇怪,因为我没有提供用户名或密码。 I gather that's because the example is running in App Engine, which provides the credentials that way.我认为这是因为该示例在 App Engine 中运行,它以这种方式提供凭据。

I've tried passing in my credentials via a properties file:我尝试通过属性文件传递我的凭据:

Credential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId("accountId")
                .setServiceAccountPrivateKeyFromP12File(
                        new File("PRIVATE_KEY_PATH"))
                .setServiceAccountScopes(scopes).build();

Storage storage = new StorageOptions.DefaultStorageFactory().create(StorageOptions.newBuilder().setCredentials(credential).build());

But that doesn't compile because the setCredentials() function needs a Credentials instance, not a Credential instance.但这不会编译,因为setCredentials()函数需要Credentials实例,而不是Credential实例。

I've been Googling and reading through the Cloud Storage API , but I still can't figure out how I'm supposed to pass in the credentials without going through a convoluted setup process.我一直在谷歌搜索并阅读Cloud Storage API ,但我仍然无法弄清楚我应该如何在不经过复杂的设置过程的情况下传递凭据。

So, my question is: what is the simplest way to provide credentials to Google Cloud storage to upload a file?所以,我的问题是:向 Google Cloud 存储提供凭据以上传文件的最简单方法什么?

For some background: I'm trying to compare and contrast Google Cloud Storage and Amazon S3.对于一些背景:我正在尝试比较和对比 Google Cloud Storage 和 Amazon S3。 I can create a program like this in S3 no problem, but for some reason I'm hitting a brick wall with Cloud Storage.我可以在 S3 中创建这样的程序没问题,但出于某种原因,我在使用 Cloud Storage 时遇到了麻烦。 Definitely appreciate any insights or basic tutorials anybody can throw my way.绝对感谢任何人都可以抛开我的方式的任何见解或基本教程。

It seems it's not so easy to create credentials from a PKCS #12 file with new Google Cloud Client Library as it used to be with the old Cloud Storage JSON API .使用新的 Google Cloud Client Library 从 PKCS #12 文件创建凭据似乎并不像以前使用旧的Cloud Storage JSON API那样容易。

The easiest way would be to use JSON format instead as described here , and then use GoogleCredentials#fromStream method to load it:最简单的方法是使用此处描述的 JSON 格式,然后使用GoogleCredentials#fromStream方法加载它:

Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("credentials.json"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

If you still want to use PKCS #12, I believe this would work:如果您仍然想使用 PKCS #12,我相信这会起作用:

PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(
    SecurityUtils.getPkcs12KeyStore(), new FileInputStream("credentials.p12"), "notasecret", "privatekey", "notasecret");
Credentials credentials = new ServiceAccountCredentials(null, "accountId", privateKey, null, null);
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

The Google Cloud client library for Java allows you to use several auth schemes, but by far the easiest is to take advantage of " Application Default Credentials ."适用于 JavaGoogle Cloud 客户端库允许您使用多种身份验证方案,但目前最简单的是利用“ 应用程序默认凭据” These are the credential associated with the service account that your app engine app runs as.这些是与您的应用引擎应用运行的服务帐户相关联的凭据。 If you use the google-cloud Java client library on App Engine or Compute Engine, the following should just work:如果您在 App Engine 或 Compute Engine 上使用 google-cloud Java 客户端库,则以下内容应该可以正常工作:

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));

This is probably the simplest way to use auth.这可能是使用 auth 的最简单方法。 If you're running the program locally and not deployed to a Google environment, you can also install the gcloud command line utility and then run gcloud auth application-default login , at which point application default credentials should enable the code above to authenticate as you without any explicit authentication logic.如果您在本地运行该程序并且未部署到 Google 环境,您还可以安装gcloud命令行实用程序,然后运行gcloud auth application-default login ,此时应用程序默认凭据应使上述代码能够像您一样进行身份验证没有任何明确的身份验证逻辑。

If you want to programmatically specify a specific service account and have the JSON key file associated with it, you can do so explicitly like so:如果您想以编程方式指定特定的服务帐户并将 JSON 密钥文件与其关联,您可以像这样明确地这样做:

Storage storage = StorageOptions.newBuilder()
    .setCredentials(ServiceAccountCredentials.fromStream(
         new FileInputStream("/path/to/my/key.json")))
    .build()
    .getService();

You can also specify the path to the service account private key by using the environment variable GOOGLE_APPLICATION_CREDENTIALS .您还可以使用环境变量GOOGLE_APPLICATION_CREDENTIALS指定服务帐户私钥的路径。 So something like:所以像:

$> GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json java MyApp

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

相关问题 Google Cloud Storage API无法在App Engine上获取应用程序默认凭据,以查找Compute Engine错误 - Google Cloud Storage API cannot get Application Default Credentials on App Engine looking for Compute Engine error 应用程序凭据在 Google Cloud Vision API 中不可用 - Applications Credentials not avaliable in Google Cloud Vision API 使用 Java 上的目标凭据进行 Google Cloud Storage URL 签名 - Google Cloud Storage URL signing with target credentials on Java 向 Spring Cloud GCP 提供凭据的替代方法 - Alternate way of providing Credentials to Spring Cloud GCP openPrefetchingReadChannel无法在Google云端存储客户端API中使用 - openPrefetchingReadChannel is not working in Google Cloud Storage Client API Google Cloud Storage Java API-删除文件 - Google Cloud Storage Java API - Deleting a file 从Google Cloud Storage API Java迁移 - Migrating from the Google Cloud Storage API java 从Google Cloud Storage Java API上传Firebase存储 - firebase storage upload from google cloud storage java api 有没有办法将 com.google.cloud.storage.Storage 转换为 com.google.api.services.storage.Storage? - is there a way to convert com.google.cloud.storage.Storage to com.google.api.services.storage.Storage? 如何使用 Google Cloud API - 应用程序默认凭据进行文本检测 - how to use Google Cloud API - Application Default Credentials for text detection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM