2

How to get gcloud access token programmatically in Java which we can get from this command gcloud auth print-access-token.

Something similar like this python code

nomadSK25
  • 2,350
  • 3
  • 25
  • 36

1 Answers1

3

You can do like that

import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;


public class Sandbox{

    public static void main(String[] args) throws IOException {

        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        System.out.println(credentials.getAccessToken());
    }
}

with that dependency

        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>1.1.0</version>
        </dependency>
guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
  • 1
    Hi, this has not worked out for us. Instead of getting the token, we get a warning message in the logs: Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/. – Nikhil VJ Mar 17 '23 at 05:43
  • It does not work? Or is it working + warning message? – guillaume blaquiere Mar 17 '23 at 08:25
  • 1
    wasn't working; the value came as null. And it would print a warning message. But we solved it, and it's been shared at a few other places too : have to do a refreshToken() in middle. I don't have the exact syntax as its on a colleague's machine. – Nikhil VJ Mar 18 '23 at 09:25