【问题标题】:secure google places api key安全的 Google Places api 密钥
【发布时间】:2020-02-11 15:21:46
【问题描述】:

我有一个带有 React 元素的 HTML 项目(在 html 中传递反应脚本标签),我需要使用谷歌地图 url 保护脚本中的 api 密钥。我是新手,我不确定这是否可能? 我试过'dotenv''dotenv webpack'

结果:我可以访问我在 .env 中定义的 API-KEY,但只能在终端中通过运行 $ node -r dotenv/config ./src/index.js

// ./src/index.js
console.log(process.env.API_KEY)
  

我尝试将它存储在一个变量中,并将一个新的脚本标签插入到 HTML 中,如下所示:

// ./src/index.js
require('dotenv-webpack');

var newScript = document.createElement("script");
newScript.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.S3_API}&libraries=places`;
newScript.type = "text/javascript";
target.appendChild(newScript);

我收到Uncaught ReferenceError: require is not defined at index.js

我也试过HtmlWebpackPlugin:

// ./webpack.config.js
const Dotenv = require('dotenv-webpack');
const path = require('path');


module.exports = {
  plugins: [
    new Dotenv({
      path: './.env', // Path to .env file (this is the default)
      safe: true
      }), // load .env.example (defaults to "false" which does not use dotenv-safe))
    new HtmlWebpackPlugin({
          template: './web/web.html',
          title: 'Custom template using html-loader',
          environment: {
            'GOOGLE_PLACES_API': process.env.GOOGLE_PLACES_API;
          })
    ]
};
<!-- ./web/web.html -->
...
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<%= htmlWebpackPlugin.options.environment %>&libraries=places"></script>

...

不胜感激任何帮助或建议

【问题讨论】:

  • 从根本上说,如果您想从浏览器发出 API 请求,那么 API 密钥必须以某种方式在浏览器中可见,这意味着您的服务器需要将其发送到浏览器,这意味着您根据定义公开公开您的 API 密钥。没有办法“保护”它。 — 有一些 Google API 旨在以这种方式使用,而 API 密钥并非旨在“安全”。可能有其他 API 是您一开始不应该仅使用私钥从浏览器访问的。

标签: html reactjs dotenv


【解决方案1】:

有多种方法可以保护您的 API 密钥,您不必隐藏它们 相反,限制您的 API 密钥:您可以通过将 API 密钥限制为特定 IP 地址、引荐来源网址或移动应用程序和特定 API 来最好地保护您的 API 密钥,因为这可以显着降低密钥泄露的影响。

在此链接中,您可以找到有关Google API Keys best practices的更多详细信息

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2015-04-01
    相关资源
    最近更新 更多