以下脚本使用简单的 AJAX 和 Javascript 从 API 查询信息并将其输出到 HTML 中。
API 的 token 在 Javascript 中公开。在我看来,这是不安全的,因为任何可以访问该页面的人都可以看到该 token 。如果这种方法不安全,是否有其他方法来隐藏 token ?理想情况下,如果需要,我想使用 Javascript、HTML 和 PHP。现有的脚本非常简单,所以我想知道是否有一种相对简单的方法来保护 token ..而不是必须添加大量额外的新代码或方法。
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.eventbriteapi.com/v3/events/eventid/?
token=TOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (data) {
console.log(data);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
</script>
<div id="eventbrite"></div>
</body>
</html>
最佳答案
您可以使用 PHP 在您的服务器上制作一个简单的代理脚本!
然后,您的 JavaScript 将调用此脚本,包括事件 ID,而 GET 参数中不包含任何其他内容,因此调用您的 PHP 代理将类似于 /proxy.php?eventid=123
为了进一步简化这个示例,您可以利用 $_SESSION
等来确保您的用户在访问之前已经访问过该页面,并且每个页面加载只允许 1 个请求或类似的内容。
我已经准备了一个示例,但您必须对其进行修改以满足您的需求!
<?php
//Get event ID you want to request:
$eventID = isset($_GET['eventid']) ? $_GET['eventid'] : FALSE;
//Exit if no ID provided:
if (!$eventID) {
exit('No ID Provided.');
}
//Set your token:
$token = '<YOUR_TOKEN_HERE>';
//Set url, %s will be replaced later:
$url = 'https://www.eventbriteapi.com/v3/events/%s/?token=%s';
//Set url, pass in params:
$request_uri = sprintf($url, $eventID, $token);
//Try to fetch:
$response = file_get_contents($request_uri);
//Set content-type to application/json for the client to expect a JSON response:
header('Content-type: application/json');
//Output the response and kill the scipt:
exit($response);
资源: What is a Proxy (Wikipedia)
更新: JavaScript:
$.getJSON('/proxy.php', {eventid: '<id_here>'}, function(response){
console.log(response);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
关于javascript - 在Javascript中传递API token : How to Keep it Secure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024518/