【问题标题】:Google Translation API v2: Allowing certain HTTP referrersGoogle Translation API v2:允许某些 HTTP 引荐来源网址
【发布时间】:2018-03-23 16:27:50
【问题描述】:

我正在使用客户端 Google 的翻译 API (v2),这意味着我的 API 密钥将对所有人公开可见。我正在通过 AJAX 调用 /translate 方法。

在谷歌下>凭据>API密钥->密钥限制->应用程序限制

我希望只允许从 www.aliceandbob.com 域调用 API。

在以下位置添加此域后:HTTP 引荐来源网址(网站)。我收到 403 禁止错误,但是当我在我的 http 请求中手动设置 http referer 标头时,它会通过,API 会回复我。

    function sendPost($data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://translation.googleapis.com/language/translate/v2");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
-->       curl_setopt($ch, CURLOPT_REFERER, "http://www.aliceanbob.com");
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

并像传递数据一样

$data = array('q' => '这是世界', 'target' => 'de', 'key' => "#my_api_key#");

响应 OK 200。

但是当我删除时:

curl_setopt($ch, CURLOPT_REFERER, "http://www.aliceandbob.com");

我得到了回应:

403 Forbidden Requests from referer \u003cempty\u003e 被阻止。

知道如何防止只有一个网站(域)可以正确调用 API 调用,但不让任何其他人手动设置 http 引用和行为域(www.aliceandbob.com)? p>

【问题讨论】:

  • 这看起来像是在 php 服务器中运行的 php 代码,因此您的 API 密钥不会对所有人可见。我错过了什么吗?无论如何,有一个 github issue 在那里你可以看到默认情况下没有设置referer header,你必须通过它。是否有某些原因导致这对您不起作用?

标签: http google-api google-translate


【解决方案1】:

在应用程序限制 - HTTP 引荐来源网址(网站)中,您必须添加:http://www.aliceandbob.com/* 或:http://*.aliceandbob.com/*

【讨论】:

    猜你喜欢
    • 2015-12-12
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多