保护AJAX- PHP web服务调用


Securing a AJAX->PHP web service call

我正试图找到一种使用AJAX保护web服务调用的方法。web服务处理联系人表单并调用PHP, PHP使用邮件函数发送电子邮件,而不需要HTTP请求。

我把我的一些代码贴在下面,这样你就能更好地理解我的问题。我试图通过HTTP请求阻止对服务的直接调用,导致我的邮件服务器在每次请求页面时都工作。

// Data is compiled into datastr...
var datastr = 
'input_name=' + encodeURI(input_name) + 
'&input_email=' + encodeURI(input_email) +
'&input_organization=' + encodeURI(input_organization) +
'&input_title=' + encodeURI(input_title) +
'&input_phone=' + encodeURI(input_phone) +
'&input_comments=' + encodeURI(input_comments);
 // AJAX is called with datastr param...
 $.ajax({
     type: "POST",
     url: "../common/contact-form-logic.php",
     data: datastr,
     cache: false,
     success: function(resp) {.... etc

这是PHP文件服务

$input_name = urldecode($_REQUEST['input_name']);
$input_email = urldecode($_REQUEST['input_email']);
$input_organization = urldecode($_REQUEST['input_organization']);
$input_title = urldecode($_REQUEST['input_title']);
$input_phone = urldecode($_REQUEST['input_phone']);
$input_comments = urldecode($_REQUEST['input_comments']);
$to = "xxxxxxxxxxxxxxxxx";
$subject = "Contact form entry from xxxxxxxxxx.com";
$message = $input_name."'n".$input_email."'n".$input_organization."'n".$input_title."'n".$input_phone."'n".$input_comments;
if(mail($to, $subject,$message)){
    echo "1";
}

我正在自学安全,发现自己遇到了类似的情况,我是这样做的:

*免责声明我不是安全专家,但我觉得这总比什么都没有好。

  1. 确保有post
  2. 检查xmlhttprequest头
  3. 然后我验证了HTTP_REFERER
  4. 然后我检查了令牌,我生成了他们会话的一部分(示例如下)

    session_start();
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token'])
    {
        /* Valid Token */
    }
    
  5. 我检查了$_POST键对白名单,以确保我有我需要的一切

这里有一个例子

// No post no dice!
if( empty($_POST) )
    die('error no post');
// Check for xmlhttprequest header
// I want to make sure this post came from an ajax call.
if( empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
    die('error invalid ajax request');
// Check to make sure the ajax request came from yourdomainhere.com
if( strpos($_SERVER['HTTP_REFERER'], 'yourdomainhere') === FALSE )
    die('error invalid http ref');
// DIE, if no token is present or token isn't equal to $_SESSION token.
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token'])
    die('error invalid token');
// Check to make sure all POST array keys I need exist for my script
$vars_needed = array("input_name", "input_email", "input_organization", "input_title", "input_phone", "input_comments");
foreach($vars_needed as $need) {
    if(!array_key_exists($need, $_POST))
        die('error invalid post');
}

你想保护什么?消息的内容还是邮件功能的访问?

对于前者,您需要使用HTTPS