小程序支付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端點獲取一些有關(guān)天氣的JSON,一些書評或類似的簡單內(nèi)容。
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上。 然后發(fā)生了壞事 。
"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
您應(yīng)該使用后端服務(wù)器作為中繼來為您獲取API結(jié)果,然后將其傳遞給您的前端
新問題 (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?!
您只是想為您的投資組合做一個前端演示! 您尚未了解有關(guān)后端技術(shù)的任何信息! 為什么這么難?!
演示版 (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.
我經(jīng)常遇到此問題,以至于我決定停止提出愚蠢的駭客,并實施一個使用最少的后端代碼的解決方案。
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.
在此演示中,我設(shè)置了一個后端,用于偵聽POST請求并將其發(fā)送到GoodReads API 。 要使用此功能,您需要實現(xiàn)自己的前端,該前端可以將適當(dāng)?shù)腜OST請求發(fā)送到此后端。 您的前端不會直接與GoodReads通信,因此不會暴露任何API密鑰。
你會需要 (You will need)
Node (this has been tested with v10.16.0, later versions will be fine, earlier ones may encounter problems)
節(jié)點 (已通過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包含您需要了解的所有內(nèi)容,包括安裝和設(shè)置。
I've included the key points here for convenience:
為了方便起見,我在此處列出了關(guān)鍵點:
自述文件 (README.md)
Install dependancies:
安裝依賴關(guān)系:
npm i
npm i
You need to create your own .env file for your key:
您需要為密鑰創(chuàng)建自己的.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=AABBCCDDEEFF00112233445566778899Now run the server:
現(xiàn)在運行服務(wù)器:
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!
在瀏覽器中,導(dǎo)航到localhost:3000以確認(rèn)服務(wù)器正在運行。 您應(yīng)該會看到一個簡單的Hello World!
接下來是什么? (What next?)
Now read the app.js file thoroughly.
現(xiàn)在,徹底閱讀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.
我對代碼進行了重注釋,以幫助您了解以前沒有多少節(jié)點/表達式的情況。
// 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 secondmax: 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 goodreadsconst searchString = `q=${req.query.q}`;// It uses node-fetch to call the goodreads api, and reads the key from .envconst 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.booksconst 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上關(guān)注他: 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設(shè)置為GET并將其粘貼在url中: localhost:3000/api/search?q=hobbit
Postman will show you the JSON response below.
郵遞員將在下面顯示JSON響應(yīng)。
您如何在前端使用它? (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.
這個簡單的應(yīng)用程序正在/api/search監(jiān)聽發(fā)布請求,因此可以像以前使用原始api的方式在前端應(yīng)用程序中與之交互。
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端點/方法,則需要考慮如何自己實現(xiàn)它們!
代管 (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.
這是為了響應(yīng)論壇上的討論而匆忙進行的。 如果您發(fā)現(xiàn)本文或示例代碼中有任何問題,請隨時回復(fù)啟動所有內(nèi)容的論壇主題 。 我將繼續(xù)撰寫本文,并回購最新的改進內(nèi)容。
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與我聯(lián)系 。
翻譯自: https://www.freecodecamp.org/news/private-api-keys/
小程序支付api密鑰
總結(jié)
以上是生活随笔為你收集整理的小程序支付api密钥_如何避免在公共前端应用程序中公开您的API密钥的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到很多蚂蚁是怎么回事
- 下一篇: 谷歌浏览器bug调试快捷键_Bug压榨初