【问题标题】:Oauth2 timeout with google API使用谷歌 API 的 Oauth2 超时
【发布时间】:2016-06-21 10:04:41
【问题描述】:

我使用 Oauth2 在基于 introductory quick start guide 的 Google Calendar API 上进行身份验证

我现在在 Web 服务器上运行它,并将回调端口设置为 9999,我也在 GCP 控制台中输入了该端口。

我在日志文件中获得了链接,并且能够在服务器上进行身份验证,并且应用程序工作正常。但是,这似乎在大约 20 分钟后超时,当我访问该站点时,日志文件会为我提供另一个 URL 进行身份验证。我正在创建一个日历小部件,所以一旦它上线,我显然不希望它过期,我只想设置一次。

StoredCredential 文件正在服务器上正确创建。我正在运行 tomcat 7,所以这个文件是用户 /usr/share/tomcat7/.credentials/

在出现“超时”之前从不同的 IP 地址访问该应用时,该应用运行良好

我用于验证的代码如下。根据文档,使用 DataStoreFactory 为 FileCredentials 创建 GoogleAuthorizationCodeFlow 对象应该表明我们已经过身份验证。

docs 还声明“访问令牌通常具有 1 小时的到期日期,在此之后如果您尝试使用它会收到错误消息。GoogleCredential 会自动“刷新”令牌,这很简单意味着获得一个新的访问令牌。”

我还尝试在凭证对象上手动设置超时。 Google docs 声明 setExpiresInSeconds() “设置访问令牌的生命周期(以秒为单位)(例如 3600 表示一小时)或 null 表示无。”我已经尝试过 null、LONG.MAX 和 1 年。所有这些导致消息“请在浏览器中打开以下地址:”在大约 45 分钟后显示在日志中。使用 getExpiresInSeconds() 方法,我可以确认超时设置为我的预期值。

文档还指出,应该在 GoogleAuthorizationCodeFlow 中将 access_type 设置为离线,我在下面展示了我正在执行的操作。

    public static Credential authorize() throws IOException {
    InputStream in = GoogleCalendarService.class.getClassLoader().getResourceAsStream("/client_secret.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));


    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
            .setAccessType("offline")
            .build();


    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setHost(REDIRECT_URI).setPort(9999).build()).authorize("user");

    return credential;
}

【问题讨论】:

    标签: java oauth-2.0 google-calendar-api


    【解决方案1】:

    对于遇到此问题的任何人,我的刷新令牌实际上是 Null。我撤销了我的令牌并不得不将批准提示设置为“强制”,如下所示:

            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
                .setAccessType("offline")
                .setApprovalPrompt("force")
                .build();
    

    创建凭证后使用:

            Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setHost(REDIRECT_URI).setPort(9999).build()).authorize("user");
    

    然后我能够做到:

    credential.getRefreshToken()
    

    这表明令牌是非空的。默认的过期时间似乎是 3600 秒,当令牌剩余

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2018-04-10
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多