正确存储 Google OAuth 访问令牌

Correctly storing Google OAuth access token

我即将开始使用 Google 的日历 API,我要求访问我的用户的日历。在 php docs example 中,令牌存储在一个文件中 (token.json),但在我的例子中,每个用户都可以拥有一个访问令牌,所以我想将它存储在用户的数据库中 table .

访问令牌将在一小时后过期。没有理由将访问令牌存储在您的数据库中。您应该存储的是您的刷新令牌。您的应用程序可以使用刷新令牌根据需要请求新的访问令牌。

建议存储 token.json 的内容,以便更轻松地向 php clinet 库提供该对象。将 file_get_contents($tokenPath) 替换为从数据库中读取的内容。

  • 将其存储在数据库中安全吗?

在数据库中存储令牌是标准的 prosecure。应该是安全的。任何入侵您的数据库的人都需要您的客户端 ID 和客户端密码来使用存储在那里的刷新令牌请求新的访问令牌。

  • 存储前需要加密吗?

你可以,但老实说我不介意。

我所做的是将它保存在数据库中并使用端点https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${your_token} to validate if the token I have in the database is still alive, if I don't get another token with the following endpoint https://www.googleapis.com/oauth2/v4/token?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token,这样我就尽可能地保留了活动令牌。