且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

OAuth2 和 Google API:访问令牌过期时间?

更新时间:2023-02-16 08:07:45

您不应该根据访问令牌的特定生命周期来设计您的应用程序.假设它们(非常)短命.

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

但是,在成功完成 OAuth2 安装应用程序流程后,您将获得一个刷新令牌.此刷新令牌永不过期,您可以根据需要使用它来交换访问令牌.保存刷新令牌,并使用它们按需获取访问令牌(然后应立即用于访问用户数据).

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

尽管上面有我的评论,但有两种简单的方法可以获取访问令牌过期时间:

My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. 当您交换刷新令牌(使用/o/oauth2/token 端点)时,它是响应 (expires_in) 中的一个参数.更多详情.
  2. 还有一个API可以返回access_token的剩余生命周期:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

这将返回一个包含 expires_in 参数的 json 数组,该参数是令牌生命周期中剩余的秒数.

This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.