Refresh Google OAuth2 Token Automatically

sim*_*otz 7 javascript google-api google-oauth google-identity

I'm trying implement a photo uploading to Google Drive feature (using the Google Drive API and GIS) into a web app that I'm working on, but can't seem to figure out how to keep a user authenticated for longer than the designated expiry time of the access token (which is 1 hour) without prompting the user or opening a popup.

The sample code provided at https://github.com/googleworkspace/browser-samples/blob/master/drive/quickstart/index.html forces the user to click a "refresh" button to get a new token, but this means I would have to force users to sign in every hour, which isn't ideal (since users are likely going to be using the app for periods longer than an hour at a time).

According to https://developers.google.com/identity/oauth2/web/guides/use-token-model#token_expiration, this appears to be intentional. However, after looking around quite a bit, I found that one could supposedly use a refresh token to generate a new access token that expires after another hour. Assuming you generate a new token every 45 minutes or so (which another Google article actually suggested, but I can't seem to find it now), then you should never have to worry about this re-authentication.

However, I can't figure out how to get a refresh token.

Not receiving Google OAuth refresh token suggests sending access_type=offline as a query parameter, but I'm not using any redirects, and the aforementioned documentation for initTokenClient and requestAccessToken don't make any mention of an access_type parameter.

The closest I've gotten is calling the requestAccessToken method periodically, but this still brings up a popup for the user to sign in again, which is what I'm trying to avoid. Even using requestAccessToken({ prompt: "" }) still brings up this popup window, but it at least logs in without any user input. Is there any way to disable this popup window entirely?

Worst case scenario, I force the user to re-authenticate every hour, but this seems like it would make for a less-than-ideal UX. Any help is appreciated.

小智 8

我已经逐步浏览了 GIS 库代码,并且可以确认提示 ='' 和提示 ='none' 没有按照 requestAccessToken 文档暗示的方式实现。GIS 始终打开一个弹出窗口。提示参数仅更改弹出窗口中发生的情况。GIS 中也没有令牌存储或缓存功能,仅在弹出窗口中。

当前的提示参数行为看起来是基于OAuth 2.0 流程比较表设计的。仅当用户调用需要访问令牌的操作时,才应刷新访问令牌。

这给我们带来了非常糟糕的用户体验,弹出窗口必须每小时左右短暂打开和关闭一次。另一种方法是使用授权代码流程。但它需要实现一种机制将访问令牌从后端发送回客户端。

  • 这使得纯客户端 Web 应用程序不可行。我对尝试迁移我的应用程序深表遗憾,并失去了对 Google 的尊重。我正在考虑完全切换架构。 (4认同)

小智 -1

按钮流程和同意弹出行为是为了让浏览器获取访问令牌而故意设计的,当将设置提示配置为空字符串时,将抑制每个请求的用户弹出窗口:prompt=''。

如果您想在用户不在场的情况下代表用户执行操作,或者必须通过手势(例如,按下按钮。