如何在数据库中存储 OAuth 2 访问令牌?

How to store OAuth 2 access tokens in a database?

我看到了很多这方面的话题,但没有具体说明如何去做。

我目前正在让用户通过 OAuth2 向第三方进行身份验证,我正在 return 中获取访问令牌。

我想长期存储此访问令牌,因此我正在使用数据库。

我的问题是如何处理此数据库条目以确保安全。

我无法对它进行哈希处理(就像密码一样),因为我需要能够读取和使用原件来代表用户呼叫第 3 方。

所以,我只能保持原样,寻找一种双向加密方法(是否有 best/recommended npm 包?)或我不知道的其他解决方案。

我对访问令牌的安全性没有经验 - 所以不知道最佳途径,希望能提供任何见解。

谢谢

I would like to store this access token for a long time and so I am using a database to do so

一个解决方案是在将数据保存到数据库之前对数据进行加密,并在每次需要访问时对其进行解密。在你的情况下,我认为对称加密是正确的选择,因此你需要有一个必须始终保持安全的私钥。此类加密最常用的算法是 Advanced Encryption Standard,也为 AES 所知,对于您的用例,建议使用 AES-256 实现。

而包含流程可视化表示的 this question on Security Stack Exchange does not address exactly your scenario, the answers to it may help you to better understand the flow to encrypt/decrypt the data in a database field. This answer 可能是您想首先查看的内容。

既然您已经对流程有了直观的了解,您可能想阅读 this article,它会引导您完成在数据库中存储敏感数据的基本加密策略:

To safely store your data in a database, you’d start by generating a strong secret key value in a byte array. This is best generated programmatically. This single key can be used to encrypt all of the data you’d like to store.

When you perform an encryption operation you initialize your Encryptor with this key, then generate a new, unique Initialization Vector for each record you’re going to encrypt.

When your application needs to work with the data, the IV is included in the data row which can be used in conjunction with the private key to decrypt the data for use in the software.

这时候你一定对如何在数据库中保护你的令牌有了更好的了解,如果允许的话,我想在我走之前提出一个建议和一个警告......

首先,我强烈建议您仅支持通过安全通信通道(即 https)进行通信。现在没有理由不使用 https,SSL 证书现在免费 Lets-encrypt

I cannot hash it (as I would a password) as I need to be able to read and use the original to call the 3rd party on behalf of the user.

基于此,我假设您的节点服务器是唯一一个代表用户调用第三方服务数据然后将自己作为 API 暴露给使用它的客户端,可能是网站 and/or 移动应用程序。

这是真的我想提醒您,您的服务器可能会成为 API 滥用的对象,正如在 this series of articles 上暴露的那样:

  • Data Scraping - Automated harvesting of proprietary data from the API.
  • Account Hijack - Reuse of stolen credentials to log into accounts on your service.
  • Fake Account Factories - Automated API manipulation to create large numbers of bot controlled accounts.
  • Aggregation - Your data is aggregated with that of others as part of a commercial enterprise without permission.
  • Cheating as as Service - Web apps that allow users to cheat gamified and rewards based platforms.