小程序支付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 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上關注他: 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密鑰

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391089.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391089.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391089.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

永無止境_永無止境地死:

永無止境Wir befinden uns mitten in der COVID-19-Pandemie und damit auch im Mittelpunkt einer medialen Geschichte, die durch eine noch nie dagewesene Komplexitt und Dynamik gekennzeichnet ist. Wie kann Informationsdesign helfen, diese Explosion von Nachrich…

HDU4612 Warm up —— 邊雙聯通分量 + 重邊 + 縮點 + 樹上最長路

題目鏈接:http://acm.split.hdu.edu.cn/showproblem.php?pid4612 Warm up Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 7206 Accepted Submission(s): 1681 Problem DescriptionN planets are …

Android sqlite load_extension漏洞解析

路人甲 2015/09/25 14:540x01 sqlite load_extensionSQLite從3.3.6版本(http://www.sqlite.org/cgi/src/artifact/71405a8f9fedc0c2)開始提供了支持擴展的能力,通過sqlite_load_extension API(或者load_extensionSQL語句&#xf…

去除Java字符串中的空格

問題:去除Java字符串中的空格 俺有一個像這樣的字符串 mysz "namejohn age13 year2001";我想要去除字符串里面的空格。我嘗試使用 trim() ,但是呢它只去除了字符串前后的空格。我也嘗試用 ("\W", “”),但是它把也給搞…

谷歌瀏覽器bug調試快捷鍵_Bug壓榨初學者指南:如何使用調試器和其他工具查找和修復Bug

谷歌瀏覽器bug調試快捷鍵As web developers, it often feels like we spend more time fixing bugs and trying to solve problems than we do writing code. In this guide well look at some common debugging techniques, so lets get stuck in.作為Web開發人員,…

吳恩達神經網絡1-2-2_圖神經網絡進行藥物發現-第1部分

吳恩達神經網絡1-2-2預測溶解度 (Predicting Solubility) 相關資料 (Related Material) Jupyter Notebook for the article Jupyter Notebook的文章 Drug Discovery with Graph Neural Networks — part 2 圖神經網絡進行藥物發現-第2部分 Introduction to Cheminformatics 化學…

再利用Chakra引擎繞過CFG

xlab 2015/12/24 15:00Author:[email protected]0x00 前言本文源自一次與TK閑聊,期間得知成功繞過CFG的經過與細節(參考:[利用Chakra JIT繞過DEP和CFG])。隨即出于對技術的興趣,也抽出一些時間看了相關的東西,結果發現了另一處繞…

論文搜索源

中國科學院文獻情報中心 見下圖 中國計算機學會推薦國際學術會議和期刊目錄 EI學術會議中心,        engieer village 轉載于:https://www.cnblogs.com/cxy-941228/p/7693097.html

重學TCP協議(10)SYN flood 攻擊

1.SYN flood 攻擊 SYN Flood(半開放攻擊)是一種拒絕服務(DDoS)攻擊,其目的是通過消耗所有可用的服務器資源使服務器不可用于合法流量。通過重復發送初始連接請求(SYN)數據包,攻擊者能…

大數據入門課程_我根據數千個數據點對互聯網上的每門數據科學入門課程進行了排名...

大數據入門課程by David Venturi大衛文圖里(David Venturi) A year ago, I dropped out of one of the best computer science programs in Canada. I started creating my own data science master’s program using online resources. I realized that I could learn everyt…

python 數據框缺失值_Python:處理數據框中的缺失值

python 數據框缺失值介紹 (Introduction) In the last article we went through on how to find the missing values. This link has the details on the how to find missing values in the data frame. https://medium.com/kallepalliravi/python-finding-missing-values-in-…

Spring Cloud 5分鐘搭建教程(附上一個分布式日志系統項目作為參考) - 推薦

http://blog.csdn.net/lc0817/article/details/53266212/ https://github.com/leoChaoGlut/log-sys 上面是我基于Spring Cloud ,Spring Boot 和 Docker 搭建的一個分布式日志系統. 目前已在我司使用. 想要學習Spring Cloud, Spring Boot以及Spring 全家桶的童鞋,可以參考學習,如…

51nod1832(二叉樹/高精度模板+dfs)

題目鏈接: http://www.51nod.com/onlineJudge/questionCode.html#!problemId1832 題意: 中文題誒~ 思路: 若二叉樹中有 k 個節點只有一個子樹, 則答案為 1 << k. 詳情參見:http://blog.csdn.net/gyhguoge01234/article/details/77836484 代碼: 1 #include <iostream&g…

重學TCP協議(11)TFO(Tcp Fast Open)

1. TFO 為了改善web應用相應時延&#xff0c;google發布了通過修改TCP協議利用三次握手時進行數據交換的TFO(TCP fast open&#xff0c;RFC 7413)。 TFO允許在TCP握手期間發送和接收初始SYN分組中的數據。如果客戶端和服務器都支持TFO功能&#xff0c;則可以減少建立到同一服…

[網絡安全] 遠程登錄

遠程登錄方式: 1.圖像化遠程登錄 做法: 運行"窗口"輸入 "mstsc " 輸入ip地址 注意: 被遠程計算機&#xff0c;必須打開遠程登錄服務: 信息面板–系統–允許遠程訪問。被遠程計算機&#xff0c;必須存在擁有遠程桌面權限的用戶。 2.命令行遠程登錄 teln…

外星人圖像和外星人太空船_衛星圖像:來自太空的見解

外星人圖像和外星人太空船By Christophe Restif & Avi Hoffman, Senior Software Engineers, Crisis Response危機應對高級軟件工程師Christophe Restif和Avi Hoffman Editor’s note: In 2019, we piloted a new feature in Search SOS Alerts for major California wild…

chrome恐龍游戲_如何玩沒有互聯網的Google Chrome恐龍游戲-在線和離線

chrome恐龍游戲Several years ago, Google added a fun little Easter egg to Chrome: if your internet went down and you tried to visit a web page, youd see the message "Unable to connect to the Internet" or "No internet" with a little pixi…

Hotpatch潛在的安全風險

屎蛋 2016/06/22 10:11author:[email protected]0x00 “Hotpatch”簡介IOS App的開發者們經常會出現這類問題&#xff1a;當一個新版本上線后發現存在一個嚴重的bug&#xff0c;有可能因為一個邏輯問題導致支付接口存在被薅羊毛的風險&#xff0c;這個時候能做的只能是趕快修復…

spring中@Inject和@Autowired的區別?分別在什么條件下使用呢?

問題&#xff1a;spring中Inject和Autowired的區別&#xff1f;分別在什么條件下使用呢&#xff1f; 我在瀏覽SpringSource上的一些博客&#xff0c;在其他一個博客中&#xff0c;那個作者用了Inject&#xff0c;但是我覺得他用Autowired也行 下面是一部分代碼&#xff1a; …

Objective-C語言的動態性

Objective-C具有相當多的動態特性&#xff0c;基本的&#xff0c;也是經常被提到和用到的有動態類型&#xff08;Dynamic typing&#xff09;&#xff0c;動態綁定&#xff08;Dynamic binding&#xff09;和動態加載&#xff08;Dynamic loading&#xff09; 一、編譯時和運行…