尝试通过 Google API 获取刷新令牌时获取 invalid_scope

Joh*_*han 15 java gmail oauth

我似乎无法将 Google API 与 Oauth 结合使用。我缺少什么?

错误信息:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_scope",
  "error_description" : "Invalid oauth scope or ID token audience provided."
}
Run Code Online (Sandbox Code Playgroud)

Java代码:

private void printLabels() {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    List<String> scopes = new ArrayList<>();
    scopes.add(GmailScopes.GMAIL_LABELS);

    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("C:\\test\\credential.json"));
    credential.createScoped(scopes);
    credential.refreshToken();      // error happens here

    String appName = "VS";
    Gmail.Builder builder = new Gmail.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName(appName);
    Gmail gmail = builder.build();

    Object o = gmail.users().labels().list("me").execute();
    System.out.println("o = " + o);
}
Run Code Online (Sandbox Code Playgroud)

谷歌API配置:

  1. 登录https://console.developers.google.com/
  2. 已创建项目
  3. 启用 Gmail API
  4. 创建服务帐户(分配所有者角色)
  5. 下载 json 凭证文件
  6. 启用 OAuth 同意屏幕 - 内部(不确定我是否需要这个,因为我只想访问我的电子邮件)
  7. 启用服务帐户域范围委派(不确定我是否需要这个)

小智 10

credential.createScoped(scopes)

返回具有给定范围的凭证对象的副本。您可以通过credential.getServiceAccountScopes()检查范围是否已设置来验证这一点。

尝试将值分配给凭证对象,例如。

credential = credential.createScoped(scopes);
Run Code Online (Sandbox Code Playgroud)

  • 从晚上9点到凌晨4点20分,我终于读到了这个答案。使用创建的范围初始化 GoolgeCredentials 的技巧是“credential = credential.createScoped(scopes);”。谢谢你! (2认同)

Mau*_*cio 8

就我而言,我在使用 Pythondefault()获取默认凭据时遇到了这个问题。gcloud auth application-default login对于使用 Kubernetes Workload Identity加载的凭证来说,它工作得很好。但是,当使用服务帐户文件时,GOOGLE_APPLICATION_CREDENTIALS我在尝试调用时遇到了这个问题credentials.refresh()。我通过显式提供作用域的scopes参数来解决这个问题。default()['https://www.googleapis.com/auth/cloud-platform']

所以我改变了:

from google.auth import default

credentials, _ = default()
Run Code Online (Sandbox Code Playgroud)

对此:

from google.auth import default

credentials, _ = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
Run Code Online (Sandbox Code Playgroud)