How to get a GCP Bearer token programmatically with Java

Viewed 347

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

1 Answers

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>
Related