使用 Javascript 通过基本身份验证使用 API,而不公开密钥对

Consume API with basic authentication using Javascript without exposing key pair

我有一个私有 API,我在其中使用基本身份验证作为我的安全层。现在 API 被我的 iOS 应用占用,所以没有人能够看到密钥对。

我正在为网络创建相同的应用程序,使用 React 和 Javascript 并且需要使用相同的 API 使用基本身份验证。

如何在 Javascript 中使用我的 API 密钥对而不将该密钥对暴露给 public?这种事情有可能吗?

TL;DR: 没有。

如果客户端需要能够直接连接到 API,则没有可靠的方法来阻止他们发现 API 密钥,因为他们必须按照设计能够访问它以便在请求中发送它。您可以采取措施对其进行混淆,方法是将其编码存储(但客户端也必须具有解码算法)。

事实上,您的 iOS 应用也是如此。有人可以对二进制文件进行逆向工程或拦截请求并查看 header,发现 API 密钥。

一个可能的“解决方案”可能是让每个客户端获得自己的 API 密钥,无论是临时的还是永久的,以某种方式锁定到他们的 account/device/session 以限制重复使用。

正如@Andrew 所提到的,这是不可能的,你可以让它更难获得,但它会在客户端代码的某个地方,这足以说明你正在公开它。

如果您对替代方案持开放态度,我建议您对第一个请求使用每用户身份验证,然后对进一步的请求使用基于令牌的身份验证。该令牌可以是 JSON Web Token,这就是我所说的流程:

这是它的工作方式,取自JWT's official documentation:

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie.

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

Authorization: Bearer <token>