简体   繁体   English

如何隐藏通常嵌入在 javascript 文件中的 api 密钥?

[英]How to hide my api key which is normally embedded in a javascript file?

I am building a small website using LiveScore api from rapidapi.com.我正在使用来自 rapidapi.com 的 LiveScore api 构建一个小型网站。 How can I hide my api key when deploying my application.部署我的应用程序时如何隐藏我的 api 密钥。 Tried.env method, serverless methods but didn't do much help.尝试过 env 方法,无服务器方法,但没有太大帮助。 I am trying the api hiding method for the first time.我第一次尝试 api 隐藏方法。 Maybe that's why I am not getting it.也许这就是我不明白的原因。 Is there any method to hide api key which is fairly simple but a decent hiding?有没有什么方法可以隐藏 api 密钥,这相当简单但隐藏得很好?

//index.js //索引.js

const options = {
method: 'GET',
headers: {
    'X-RapidAPI-Key': 'xxxxxxxxxx',
    'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};

fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?   
Category=soccer&Date=20231801&Timezone=-7', options) 
.then(
response => {
    response.json().then(
        data => {
//my code here
})

In plain client side Javascript there is not much you can do to hide API Keys.在普通客户端 Javascript 中,您无法隐藏 API 密钥。 I took a quick glance at the RapidAPI docs and also this blog post from them, but they just use the API Keys as-is without securing anything.我快速浏览了RapidAPI 文档以及他们的这篇文,但他们只是按原样使用 API 密钥,没有保护任何东西。 (lol) (哈哈)

So if you're worried about that information leaking, I would recommend you to create a backend in any backend language you prefer (it could be NodeJS, if you want to use Javascript) and use it as a proxy to make a request to that LiveScore API. If you do this you don't have to hardcode the API Keys in your client code, you could use dotenv in your backend, also you could control which endpoints to use and even add some custom basic authentication to be able to make a request.所以如果你担心信息泄露,我建议你用你喜欢的任何后端语言创建一个后端(如果你想使用 Javascript,它可以是 NodeJS)并将它用作代理来发出请求LiveScore API。如果你这样做,你不必在你的客户端代码中硬编码 API 键,你可以在你的后端使用dotenv ,你也可以控制使用哪些端点,甚至添加一些自定义基本身份验证,以便能够一个要求。

This is a basic example using NodeJS and express :这是一个使用 NodeJS 和express的基本示例:

const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();

app.use(express.json());
app.use(cors());

app.get('/api/livescore', async (req, res) => {
  try {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': process.env.RAPID_API_KEY,
        'X-RapidAPI-Host': process.env.RAPID_API_HOST
      }
    };

    const rapidApiResponse = await fetch('https://some-rapid-api-endpoint.com', options);

    const parsedResponse = await rapidApiResponse.json();

    return res.json({ data: parsedResponse });
  } catch (err) {
    return res.status(500).json({ err: err.message });
  }
});

app.listen(process.env.PORT || 3000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM