简体   繁体   English

防止通过AJAX调用直接访问文件

[英]Prevent direct access to file through AJAX call

I'm breaking my head over this issue, where I want to prevent people from direct accessing a file which I'm calling using AJAX. 在这个问题上,我想尽办法了,我想防止人们直接访问使用AJAX调用的文件。

In short: 简而言之:

  • main-script.php makes an AJAX call to ajax-request.php main-script.phpajax-request.php进行AJAX调用
  • ajax-request.php can only be called from from main_script.php 只能从main_script.php调用ajax-request.php
  • Prevent direct access to ajax-request.php 禁止直接访问ajax-request.php

I've already read similiar questions like this one , but the "accepted answer" here (like many other of the answers) seems like it shouldn't be accepted. 我已经读到这样similiar问题这一个 ,但“接受的答案”在这里(像其他许多问题的答案),好像它不应该被接受。 What got my attention however was this answer , where he's talking about using $_SESSION and hashing. 但是,引起我注意的是这个答案 ,他在这里谈论使用$_SESSION和哈希。 Now the problem is (1) that I'm skeptical if you can actually prevent people from direct accessing in this case; 现在的问题是(1)如果您真的可以阻止人们在这种情况下直接访问,我表示怀疑; (2) I can't wrap my head around on how you'd use sessions and hashing to make this happen. (2)我无法确定如何使用会话和哈希来实现这一目标。

So I would appreciate it if someone could help me out with the thinking process or give me a push in the right direction (or give advice if it's not really possible at all). 因此,如果有人可以帮助我进行思考或在正确的方向上给予我帮助(或在根本不可能的情况下提供建议),我将不胜感激。

You can't prevent me from requesting yourdomain/ajax-request.php as long as I know there is some resource on that location, however you can prevent unauthorized access to this file, similar to the way to prevent guests from members areas on your website, or any resource that requires authorization. 只要我知道该位置上有一些资源,就不能阻止我请求yourdomain/ajax-request.php ,但是您可以防止对该文件的未经授权的访问,类似于防止来宾访问您的会员区域的方法网站或任何需要授权的资源。 The deference is that I don't get an authorized access by providing a password , no I get that access to ajax-request.php only if I requested main_script.php 区别在于我没有通过提供密码来获得授权访问,不,仅当我请求main_script.php ,我才可以访问ajax-request.php

The simplest way I would do to accomplish this is with ( $_COOKIE and database) or ( $_SESSION ), for example 例如,我要做的最简单的方法是使用( $_COOKIE和数据库)或( $_SESSION

main_script.php main_script.php

$_SESSION['canRequestAjax'] = 1;

other_scripts.php other_scripts.php

unset($_SESSION['canRequestAjax']);
/* 
 remove the variable if he visited something else, 
 because he can only request the ajax-request.php RIGHT AFTER the main_script.php
*/

ajax-request.php ajax-request.php

if (empty($_SESSION['canRequestAjax'])){
    die('error'); // TODO: proper 403 response
}
unset($_SESSION['canRequestAjax']);
/* 
 remove the variable if he requested the ajax ajax-request.php file, only 1 ajax is allowed. 
NOTE: remove this line if the user may do more than 1 ajax requests when he is on
 main-script.php
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM