I am writing a class for creating authorization to Bigquery and Google Cloud Storage. In the past I have used CredentialStore which has been deprecated. I am trying to use DataStoreFactory but I discovered that it allows me to use only StoredCredential while I need a Credential. I know one can convert from Credential to StoredCredential but I am not sure how to convert them in the opposite direction (StoredCredential to Credential). I am creating my connection using for example Storage.Builder(HttpTransport transport, JsonFactory jsonFactory, HttpRequestInitializer httpRequestInitializer)
Could anyone point me in a direction about how to achieve this? Thank you!
I'm using google-oauth-client-1.22.0.jar.
I have a Java server with static Service Account credentials that authenticates with Google Cloud.
Here is the salient code that I use.
The key here is to add a
CredentialRefreshListener
which, when you successfully authenticate, then the Google OAuth client library will call and give you aStoredCredential
object which you can serialize and store. You store it, and retrieve it, to a location of your choice by writing or instantiating an implemenation of theDataStore
interface. YourDataStore
implementation is constructed using aDataStoreFactory
implementation.After building my
GoogleCredential
, then I can read the last access token, refresh token and expiration date from myDataStore
. If the access token isn't about to expire, then the Google client API will use it to log in. When it's about to expire, or this is the first time this code is called, then the Google Client API will invoke the refresh listener and it will store the first access token, refresh token and expiration date.In most cases, wherever you use Credential, you could use StoredCredential. There is only one point you would work with Credential, which is retrieving the Access Token during the OAuth callback. From there the Credential can be converted to StoreCredential and stored into the DataStore. After that storage and retrieval all works with StoredCredential.
But there are places were StoredCredential can't be used. I just encountered one trying to create the Google Drive API Service wrapper.
There is a way to get around this with the GoogleCredential object, it can be created from StoredCredential as per this answer: Stored Credential from google api to be reused java