google-cloud-platform - 使用服务帐户从 Java 应用程序访问 BigQuery 的 GCloud Auth 无法正常工作
问题描述
我想访问 BigQuery 以从我的 JAVA 应用程序的表中选择数据。首先,我创建了一个服务帐户并授予 BigQuery 管理员权限。服务帐户的 Json 作为环境变量传递,我使用如下代码(从https://cloud.google.com/docs/authentication/production获取)
static void authImplicit() {
// If you don't specify credentials when constructing the client, the client library will
// look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
Storage storage = StorageOptions.getDefaultInstance().getService();
System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
}
该方法返回 401 并带有以下错误响应:
引起:com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized { "code" : 401, "errors" : [ { "domain" : "global", "location" : "Authorization", "locationType " : "header", "message" : "需要登录。", "reason" : "required" } ], "message" : "请求缺少必需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效身份验证凭证。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。”,“状态”:“未验证”}
解决方案
从您的描述看来,您没有将 json 文件放在环境变量中描述的路径中。这是假设您在属性文件中正确描述了您的项目 ID,您已在 Google Cloud Platform 中启用了所需的 API。为了更精确地确定这一点,我需要您与我们分享您的文件夹结构和属性文件。
我建议你使用 CredentialsProvider 接口来解决这个问题
public interface CredentialsProvider {
Credentials getCredentials() throws IOException;
}
您可以在此处找到有关此界面的更多信息。
推荐阅读
- php - 给图片添加水印
- vb.net - 如何将 datagridview 中的值添加到 vb.net 中的饼图中?
- clojure - `map` 函数可以返回向量而不是列表吗?
- javascript - AJAX 调用后 JS 未执行
- javascript - 在 Rails 6 中使用 webpacker 的 Javascript (UJS) 错误
- python - Python 3.8 - 使用 binascii.a2b_uu 将字符串转换为二进制
- gnupg - GPG 不适用于 python 3.8,但适用于 3.6
- reactjs - 使用 React + Redux 加载屏幕
- git - 错误:RPC 失败;curl 18 传输关闭,在推送大回购时剩余未完成的读取数据
- java - 使用 POI 检测和设置列宽,并根据该宽度应用文本换行