Access Google Cloud Pub/Sub on Android without using credential file


In this article, we will see how to access Google Cloud Pub/Sub on android without using credentials file.

What is Pub/Sub?

Pub/Sub is a messaging service using which multiple systems can subscribe to the message produced by the host system. You can use Pub/Sub as messaging-oriented middleware.

Problem Outline

Configuring google cloud pub/sub in android requires a credential file. The credential file is generally kept inside assets or the raw folder of the project. As a result, the application is bound with only one google cloud pub/sub account. So multiple pub/sub account usages are not possible inside an application with current architecture.

Commonly used approach:

InputStream jsonCredentials = mContext.getResources().openRawResource(credentialFileName);

GoogleCredential credentials = GoogleCredential.fromStream(jsonCredentials).createScoped(Collections.singleton(PubsubScopes.PUBSUB))

In the above code snippet, we have to provide the filename which is stored in raw or asset folder.

Solution

To overcome this issue, we will follow the below steps:

1) Store Credential file content to a server

Store the contents of the credential file to a server and get the contents from the server using REST api call. You can use any authentication technique in the REST api.

2) Store the content of Credential file and process it

Store the content of the credential file which we got from the server, into local storage.

Get the content from local storage and initialise it to a string variable as shown below:

String credentialFileContent = getContentFromYourLocalStorage();

Then, initialise Credentials object as shown below:

InputStream jsonCredentials=new ByteArrayInputStream(credentialFileContent.getBytes(StandardCharsets.UTF_8));

GoogleCredential credentials = GoogleCredential.fromStream(jsonCredentials).createScoped(Collections.singleton(PubsubScopes.PUBSUB));

Now, We can use this credential object anywhere inside the code without depending on the raw or assets folder. Using this approach we can create as many instances as we want dynamically.

This approach will also work with the on-premise architecture, each and every time we don’t have to replace credential files into the raw folder.

Leave A Comment

Your email address will not be published. Required fields are marked *