小程序支付api密钥_如何避免在公共前端应用程序中公开您的API密钥

小程序支付api密钥

问题 (The Problem)

All you want to do is fetch some JSON from an API endpoint for the weather, some book reviews, or something similarly simple.

您要做的就是从API端点获取一些有关天气的JSON,一些书评或类似的简单内容。

The fetch query in your front-end is easy enough, but you have to paste your secret API key right there in the front-end code for anybody to find with a trivial amount of digging!

前端中的获取查询非常容易,但是您必须在前端代码中将您的秘密API密钥粘贴到前端代码中,以便任何人都能通过少量的挖掘找到它!

Also, pushing your API keys to your GitHub repository is a major problem: Dev put AWS keys on Github. Then BAD THINGS happened.

另外,将API密钥推送到GitHub存储库也是一个主要问题: Dev将AWS密钥放在Github上。 然后发生了坏事

"Why is this so hard?!" – You, probably 15 minutes ago
“为什么这么难?!” –您,大约15分钟前

解决方案 (The Solution)

You should use a back-end server as a relay to fetch the API results for you and then pass them on to your front-end

您应该使用后端服务器作为中继来为您获取API结果,然后将其传递给您的前端

新问题 (The New Problem)

You're just trying to do a front-end demo for your portfolio! You haven't learned anything about back-end technologies yet! Why is this so hard?!

您只是想为您的投资组合做一个前端演示! 您尚未了解有关后端技术的任何信息! 为什么这么难?!

演示版 (Demo)

I've encountered this problem often enough that I've decided to stop coming up with silly hacks and implement a solution that works with minimal back-end code.

我经常遇到此问题,以至于我决定停止提出愚蠢的骇客,并实施一个使用最少的后端代码的解决方案。

In this demo I set up a back-end that listens for POST requests and sends them to the GoodReads API. To use this you need to implement your own front-end that can send the appropriate POST request to this back-end. Your front-end won't communicate with GoodReads directly, so no API key is exposed.

在此演示中,我设置了一个后端,用于侦听POST请求并将其发送到GoodReads API 。 要使用此功能,您需要实现自己的前端,该前端可以将适当的POST请求发送到此后端。 您的前端不会直接与GoodReads通信,因此不会暴露任何API密钥。

你会需要 (You will need)

  • Node (this has been tested with v10.16.0, later versions will be fine, earlier ones may encounter problems)

    节点 (已通过v10.16.0进行了测试,以后的版本会很好,早期的版本可能会遇到问题)

  • git

    吉特

  • This repo: https://github.com/JacksonBates/example-goodreads-api-relay

    这个仓库:https://github.com/JacksonBates/example-goodreads-api-relay

开始吧 (Get started)

git clone https://github.com/JacksonBates/example-goodreads-api-relay.git

git clone https://github.com/JacksonBates/example-goodreads-api-relay.git

The README.md contains everything you should need to know, including installation and set up.

README.md包含您需要了解的所有内容,包括安装和设置。

I've included the key points here for convenience:

为了方便起见,我在此处列出了关键点:

自述文件 (README.md)

Install dependancies:

安装依赖关系:

npm i

npm i

You need to create your own .env file for your key:

您需要为密钥创建自己的.env文件:

cp .env.example .env

cp .env.example .env

Then open the new .env file and paste your keys in the correct spot.

然后打开新的.env文件,然后将密钥粘贴到正确的位置。

Example:

例:

GOODREADS_API_KEY=AABBCCDDEEFF00112233445566778899

Now run the server:

现在运行服务器:

node app.js

node app.js

In the browser, navigate to localhost:3000 to confirm the server is running. You should see a simple Hello World!

在浏览器中,导航到localhost:3000以确认服务器正在运行。 您应该会看到一个简单的Hello World!

接下来是什么? (What next?)

Now read the app.js file thoroughly.

现在,彻底阅读app.js文件。

I've commented the code heavily to help you understand what is going on if you haven't seen node / express much before.

我对代码进行了重注释,以帮助您了解以前没有多少节点/表达式的情况。

// app.js

// These import necessary modules and set some initial variables
require("dotenv").config();
const express = require("express");
const fetch = require("node-fetch");
const convert = require("xml-js");
const rateLimit = require("express-rate-limit");
const app = express();
const port = 3000;

// Rate limiting - Goodreads limits to 1/sec, so we should too

// Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set('trust proxy', 1);

const limiter = rateLimit({
	windowMs: 1000, // 1 second
	max: 1, // limit each IP to 1 requests per windowMs
})

//  apply to all requests
app.use(limiter)

// Routes

// Test route, visit localhost:3000 to confirm it's working
// should show 'Hello World!' in the browser
app.get("/", (req, res) => res.send("Hello World!"));

// Our Goodreads relay route!
app.get("/api/search", async (req, res) => {
	try {
		// This uses string interpolation to make our search query string
		// it pulls the posted query param and reformats it for goodreads
		const searchString = `q=${req.query.q}`;

		// It uses node-fetch to call the goodreads api, and reads the key from .env
		const response = await fetch(`https://www.goodreads.com/search/index.xml?key=${process.env.GOODREADS_API_KEY}&${searchString}`);
		//more info here https://www.goodreads.com/api/index#search.books
		const xml = await response.text();

		// Goodreads API returns XML, so to use it easily on the front end, we can
		// convert that to JSON:
		const json = convert.xml2json(xml, { compact: true, spaces: 2 });

		// The API returns stuff we don't care about, so we may as well strip out
		// everything except the results:
		const results = JSON.parse(json).GoodreadsResponse.search.results;

		return res.json({
            success: true,
            results
        })
	} catch (err) {
		return res.status(500).json({
			success: false,
			message: err.message,
		})
	}
})

// This spins up our sever and generates logs for us to use.
// Any console.log statements you use in node for debugging will show up in your
// terminal, not in the browser console!
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Update: Huge thanks to Gouri Shankar Kumawat for contributing a PR that improved this code! You can follow him on Twitter at @dev_gskumawat, or on GitHub: gskumawat0

更新 :非常感谢Gouri Shankar Kumawat贡献了改进此代码的PR! 您可以在Twitter上@dev_gskumawat或在GitHub上关注他: gskumawat0

测试API中继 (Test the API relay)

Use Postman to test the API.

使用Postman测试API。

Set Postman to GET and paste this in the url: localhost:3000/api/search?q=hobbit

将Postman设置为GET并将其粘贴在url中: localhost:3000/api/search?q=hobbit

Postman will show you the JSON response below.

邮递员将在下面显示JSON响应。

您如何在前端使用它? (How do you use this in your front end?)

This simple app is listening for post requests at /api/search, so interact with it in your front end app the way you have been previously with the original api.

这个简单的应用程序正在/api/search监听发布请求,因此可以像以前使用原始api的方式在前端应用程序中与之交互。

This is only configured to handle search queries - if you want to use other Goodreads API endpoints / methods, you'll need to think about how you implement them yourself!

它仅配置为处理搜索查询-如果您想使用其他Goodreads API端点/方法,则需要考虑如何自己实现它们!

代管 (Hosting)

You can't deploy your front-end and still have this on localhost - obviously you need to deploy this, too.

您无法部署前端,而仍在本地主机上拥有它-显然您也需要部署它。

I recommend Heroku.

我推荐Heroku

额外信用 (Extra Credit)

If you wanted to extend this, you could consider how you might only make this accessible from a restricted range of IP addresses to increase the security - which was outside of the scope of this tutorial / demo.

如果要扩展此功能,可以考虑如何仅允许从有限的IP地址范围访问此地址,以提高安全性-这超出了本教程/演示的范围。



This was hastily put together in response to a discussion on the forum. If you spot any issues in this post or the example code, please don't hesitate to reply to the forum thread that started it all. I'll keep the article and repo up-to-date with improvements.

这是为了响应论坛上的讨论而匆忙进行的。 如果您发现本文或示例代码中有任何问题,请随时回复启动所有内容的论坛主题 。 我将继续撰写本文,并回购最新的改进内容。

Feel free to submit PRs if you have valuable contributions to make :)

如果您有宝贵的贡献,请随时提交PR:

You can also reach out to me via Twitter: @JacksonBates.

您也可以通过Twitter: @JacksonBates与我联系

翻译自: https://www.freecodecamp.org/news/private-api-keys/

小程序支付api密钥

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值