我一直在我所有观点的底部做这样的事情:
<script type='text/javascript'>
$.post('php/ajax.php', {type:'session'}).done(function(data){
var session = JSON.parse(data);
$(document).ready(function(){
$.getScript('resources/redactor/redactor.js');
$.getScript('javascript/year_long_calendar.js');
$.getScript('javascript/edit_lesson_modal.js');
});
});
</script>
这对我来说非常有效。我的所有脚本都加载到单个 docReady 中,并且我的所有 ajax 都需要一个在登录时生成并存储在 $_SESSION 中的 token 。这可以阻止人们使用假 header 来访问我的 ajax 逻辑。通过这样做,我的 ajax 调用看起来像:
$.post(url:'ajax.php', {token:session.token, id:id}).done(function(data){ ... });
我还可以访问其他 session 变量
var user_id = session.user_id;
由于我从项目一开始就这样做,因此我有意将密码等任何敏感信息保留在 session 变量之外。您对此有何看法?这些是否让您感到不安全或效率极低?我意识到 $.getScript 通常被用作加载库的一种惰性方式,但我认为我已经找到了它的一个非常有效的用途。
除了 token 之外,$_SESSION 中的任何数据都不敏感,您必须登录才能获取 token 。除非有人在真实用户不在时恶意跳上一台机器,并且确切地知道我的 ajax 逻辑在哪里,它是如何工作的,我如何存储我的 session ,并在 PostMan 上伪造一个快速 header 来删除我的所有表,否则我看不到这是一个问题。
编辑: @AnotherGuy 帮助我实现了更好的解决方案。我的 ajax.php 文件现在如下所示:
<?php session_start();
include('connect.php');
include('functions.php');
// check to see if http request is ajax (easy to fake but hey might as well)
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// when the user logs in, a random number is generated and saved to $_SESSION['token'].
// this block is used to pass the token to a javascript variable securely
if($_POST['type'] == 'session'){
$session = [
'token'=>$_SESSION['token'],
'user_id'=>$_SESSION['user_id']
];
echo json_encode($session);
}
// all post requests must pass the correct token variable to step into this block and access the ajax logic
if(isset($_POST['token']) && $_POST['token'] == $_SESSION['token']){
if($_POST['type'] == 'get'){
$where = null;
if(isset($_POST['where'])){
$where = json_decode($_POST['where']);
}
$order_by = null;
if(isset($_POST['order_by'])){
$order_by = json_decode($_POST['order_by']);
}
echo json_encode(get($_POST['db'], $_POST['table'], $where, $order_by)->fetchAll());
}
if($_POST['type'] == 'put'){
$set = json_decode($_POST['set']);
echo put($_POST['db'], $_POST['table'], $set);
}
if($_POST['type'] == 'update'){
$set = json_decode($_POST['set']);
$where = json_decode($_POST['where']);
update($_POST['db'], $_POST['table'], $set, $where);
}
if($_POST['type'] == 'delete'){
$where = json_decode($_POST['where']);
delete($_POST['db'], $_POST['from'], $where);
}
最佳答案
从您描述的使用 session 的方式来看,我看不出它有任何危害,但我仍然认为它很危险。想象一下您将来从事另一个项目,然后再回到这个项目。您还记得不要在 session 中存储任何敏感信息吗?基本的经验法则是永远不要在 session 中存储敏感信息,除非它是唯一的解决方案,但这种情况很少发生。但有时犯下的错误可能会伤害你!
我会将其更改为看起来/工作方式相同的东西,但为您提供更多与 session 的解耦。如果您要获取整个 session ,您必然会检索一些永远不会被使用或永远不应该为客户端提供的信息(通过 Javascript)。我会根据您的要求创建一个页面,该页面只能提供必要的信息。这样您还可以确保只向客户端公开所需的信息。
因此,我不会请求通用的 ajax.php
文件,而是创建一个名为(或类似名称)userInfo.php
的页面。这样您还可以消除随其发送的 type
变量。
希望这可以帮助您,祝您编码愉快!
关于javascript - 我在页面加载时将整个 $_SESSION 变量放入 json 对象中。虽然这对我有用,但这是一个好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172632/