google-auth-library-java icon indicating copy to clipboard operation
google-auth-library-java copied to clipboard

Migrating old GoogleCredential object to new GoogleCredentials object for OAuth

Open z0mg opened this issue 1 year ago • 5 comments

I have a web application and obtain an auth code with which I get a refresh token. I then supply this refresh token to the library and it can obtain a new access code before I access it.

This is how I currently do it for the old version:

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.bigquery.Bigquery;

    public static final HttpTransport httpTransport = new NetHttpTransport();
    public static final JsonFactory jsonFactory = new JacksonFactory();

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets("client_id", "secret")
        .build()
        .setFromTokenResponse(new TokenResponse().setRefreshToken("refresh_token");

    credential.refreshToken();

    Bigquery bigquery = new Bigquery.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("appName").build();

And I would like to build the equivalent with a GoogleCredentials object, which the newer BigQuery library needs - how to do this?

    com.google.auth.oauth2.GoogleCredentials credentials = ??? ;

    import com.google.cloud.bigquery.BigQuery bigquery =
        BigQueryOptions.newBuilder()
            .setCredentials(credentials)
            .setProjectId(projectId)
            .build()
            .getService();

z0mg avatar Apr 25 '24 08:04 z0mg

Same question

dungthantai avatar May 05 '24 21:05 dungthantai

Any thoughts?

z0mg avatar May 17 '24 12:05 z0mg

Anyone?

z0mg avatar Jun 14 '24 07:06 z0mg

Can you try with using Application Default Credentials (ADC): https://cloud.google.com/docs/authentication/application-default-credentials

The new code with GoogleCredentials would be as simple as GoogleCredentials.getApplicationDefault(). If you wish to use clientId/clientSecret pairing, I believe you can use UserCredentials: https://github.com/googleapis/google-auth-library-java/blob/main/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java

lqiu96 avatar Jul 11 '24 18:07 lqiu96

Thank you, @lqiu96, but I need to connect to multiple accounts from the same environment (during the same JVM instance). Even if it worked, it wouldn't help me.

z0mg avatar Sep 02 '24 10:09 z0mg