如何使用 Java 以编程方式获取 GCP Bearer 令牌

问题描述 投票:0回答:2

如何在 Java 中以编程方式获取 gcloud 访问令牌,我们可以通过此命令获取

gcloud auth print-access-token

类似这样的python代码

java google-cloud-platform gcloud google-iam
2个回答
3
投票

你可以这样做

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());
    }
}

有了这种依赖性

        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>1.1.0</version>
        </dependency>

0
投票

对于遇到此问题的其他人,@Nikhil VJ 的评论让我想到了这样有效的方法:

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

public class Example {
  private static void setup() throws IOException {
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    credentials.refreshIfExpired();
    System.out.Println(credentials.getAccessToken().getTokenValue());
  }
}

credentials.refreshIfExpired()
是我所缺少的。

© www.soinside.com 2019 - 2024. All rights reserved.