限制保存在我的数据库中的特定域的PHPAPI

我创建了一个 API,它接受主机密钥或 API_KEY,然后它验证并返回 JWT 令牌。一切正常,如果没有 Hostkey,我无法访问受限路由。

问题

主要问题是如果有人将此主机密钥提供给其他人会发生什么,因为它将不再受到保护或被滥用。所以我想要做的不仅是验证主机密钥,还要验证请求来自的域。这是一种付费服务,我真正想限制的是特定域。就像谷歌对 MAP Api 所做的那样,就好像我们将该映射键添加到其他域一样,它会引发错误。

回答

做到这一点的唯一方法是检查来源和引荐来源标头。

不幸的是,服务器到服务器这不能可靠地完成,因为引荐来源和来源标头将由编码器设置,因此很容易被欺骗。对于服务器到服务器的调用,最好将允许调用 APIS 的 IP 地址列入白名单。在这种情况下,请使用诸如如何从访问者那里获取真实 IP 之类的内容?获取服务器的真实 IP 并针对列入白名单的 IP 进行验证。

假设这是浏览器中的 JS 调用,而不是服务器到服务器,并且您信任浏览器,那么真正可以做到的唯一方法是验证引用者和源头。这仍然可以被浏览器插件甚至像 Postman 这样的工具欺骗,所以我不推荐它来保证高安全性。这是用于验证来源或引用者的 PHP 示例。

$origin_url = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'];
$allowed_origins = ['example.com', 'gagh.biz']; // replace with query for domains.
$request_host = parse_url($origin_url, PHP_URL_HOST);
$host_domain = implode('.', array_slice(explode('.', $request_host), -2));
if (! in_array($host_domain, $allowed_origins, false)) {
    header('HTTP/1.0 403 Forbidden');
    die('You are not allowed to access this.');     
}

可选地,CORS 标头也很好,正如@ADyson跨域请求标头(CORS)所评论的那样,带有 PHP 标头

  • @Akhilesh if your project is a serious one and you have big concerns about this issue, you should employ a security consultant with experience of web applications and APIs. Then, when they have analysed all your requirements and constraints and use cases in greater detail than is possible here, you might get some more bespoke advice and a roadmap. Out of necessity, in this volunteer-run site, you will tend to get general advice and we don't have time to ask you about every single detail of your app in order to suggest the idea solution for your exact scenario. That's work you need to do.

以上是限制保存在我的数据库中的特定域的PHPAPI的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>