首页 > 解决方案 > 使用 access_token/refresh_token/expires_in 参数创建一个没有 flow/installApp 内容的凭证

问题描述

快速启动示例项目正在加载 *.json 凭证文件,执行授权流程,将令牌保存在另一个文件中,然后使用令牌创建凭证。我的目标是分步进行:

  1. 在交换令牌的授权码后将令牌存储在数据库中
  2. 从数据库中检索令牌
  3. 如果需要,检查凭证到期和刷新令牌,然后再次将其保存到数据库
  4. 创建一个凭证对象(不做 flow/authorizationInstalledApp 的东西)

所以我尝试了以下方法来创建带有令牌相关参数的凭证:

TokenResponse tokens = new TokenResponse();
String token = "xxxxxxxxxxxxxxx$$$$$$$$$";
tokens.setAccessToken(token);
tokens.setTokenType("bearer");
tokens.setExpiresInSeconds(3500L);
Credential credential = new 
Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(tokens);

凭证已创建,但 API 调用失败,原因如下:

401 Unauthorized { "code" : 401, "errors" : [ { "domain" : "global", "location" : "Authorization", "locationType" : "header", "message" : "Invalid Credentials", "reason " : "authError" } ], "message" : "无效凭证" }

我还在 java doc 中尝试了另一个建议:

public static Credential createCredentialWithRefreshToken(
      HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
    return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(
    transport)
    .setJsonFactory(jsonFactory)
    .setTokenServerUrl(
        new GenericUrl("https://server.example.com/token"))
    .setClientAuthentication(new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"))
    .build()
    .setFromTokenResponse(tokenResponse);
 }

这对我也不起作用。所以我的问题是:

  1. 我们可以用 access_token、refresh_token、expires 创建一个非常简单的凭证对象吗?
  2. 为什么我们必须连接 GoogleAuthorizationCodeFlow?
  3. 基于 Java 客户端库 (OAuth 2.0) 的有效凭证对象的最低要求参数是多少。

非常感谢您的任何想法/意见。

标签: javagoogle-apigoogle-oauthgmail-apigoogle-api-java-client

解决方案


推荐阅读