Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Cloud Platform pub/sub Publisher, how to supply credentials other than default application credentials

Using the com.google.cloud.google-cloud library (http://googlecloudplatform.github.io/google-cloud-java/0.21.1/index.html), I have the following code for the Google Cloud Platform pub/sub:

    TopicName topicName = TopicName.create("projectId...", "topic...");
    Publisher pub = Publisher.defaultBuilder(topicName).build();

How can I supply the credentials to be used by the publisher? I already have them in memory as they are provisioned through other means than hard coding them into a file.

All the examples for using custom credentials are as follows:

Storage storage = StorageOptions.newBuilder()
    .setProjectId(PROJECT_ID)
    .setCredentials(GoogleCredentials.fromStream(
    new FileInputStream(PATH_TO_JSON_KEY))).build();
Bucket bucket = storage.create(BucketInfo.of("myBucketName"));

But there is no PubSubOptions or PublisherOptions class to write similar code (I replace the FileInputStream with a ByteArrayInputStream).

Here's someone who has the same problem but the code sample doesn't work: https://github.com/GoogleCloudPlatform/google-cloud-java/issues/1751

like image 321
RedShift Avatar asked Aug 08 '17 07:08

RedShift


2 Answers

You can set the credentials provider on the builder:

GoogleCredentials credentials = GoogleCredentials.fromStream(
    new FileInputStream(PATH_TO_JSON_KEY)));
Publisher pub = Publisher
    .defaultBuilder(topicName)
    .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
    .build();

Now that will set the CallSettings used... but I don't think it'll set the credentials used when setting up the channel itself. (It looks like there may be differences between the Java gRPC code and the C# code I'm more familiar with.)

like image 171
Jon Skeet Avatar answered Nov 07 '22 08:11

Jon Skeet


The interface has changed slightly. You should now use:

 GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("<path-to-service-account JSON file>"));
 Publisher publisher = Publisher
            .newBuilder(topicName)
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();
like image 22
Jaap Mulder Avatar answered Nov 07 '22 09:11

Jaap Mulder