问题描述
我正在尝试通过 Google 服务帐户调用 Google Cloud DocumentAI。我有为它生成的 json 密钥,我通过 FixedCredentialsProvider
和 GoogleCredentials
对象将它加载到我的应用程序中,因为我的用例无法通过环境变量加载它。此方法曾经可以工作,但现在它会引发 UNAUTHORIZED
异常以及与没有有效 OAuth2 令牌相关的问题。当我使用 GOOGLE_APPLICATION_CREDENTIALS
环境变量测试场景时,它工作正常。是否有更改不再允许使用 FixedCredentials
方法?我还没有更新 sdk,它只是自行停止了。有没有一种以编程方式加载凭据 JSON 密钥的新方法?
解决方法
最终检查了 SDK 源代码以找到答案。通过环境变量加载和使用 GoogleCredentials
之间的区别在于,在后一种情况下它不提供 OAuth2 scope
,这是自上次测试以来已成为强制性的Google 的 DocumentAI 服务端。使用环境变量加载密钥来自提供一些默认范围的不同代码路径。我们可以在通过 GoogleCredentials
加载时手动提供相同的范围,如下所示:
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream(jsonKeyFile))
.createScoped(DocumentUnderstandingServiceSettings.getDefaultServiceScopes());
DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create(
DocumentUnderstandingServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(googleCredentials))
.build()
);
DocumentUnderstandingServiceSettings.getDefaultServiceScopes()
返回一个静态变量,该变量包含与环境变量加载方法使用的范围相同的范围,这反过来又使 DocumentAI 与手动创建的 GoogleCredentials
一起使用。