简体   繁体   English

如何使用表单令牌在一页中验证多个表单以防止CSRF攻击?

[英]How can validate multiple form In one page using form token to prevent CSRF Attacks?

Well, In my website I am using PHP unique form token to prevent CSRF attacks. 好吧,在我的网站中,我正在使用PHP唯一形式的令牌来防止CSRF攻击。 The unique form token and form token validation function is bellow : 独特的表单令牌和表单令牌验证功能如下:

// generate new token for every form
function generate_Form_Token($form_name) {        
    $token = md5(uniqid(microtime(), true));                  
    $_SESSION[$form_name.'_token'] = $token; 
    return $token;
}

// validate form request
function verifyForm ($form, $url){
    // call the form processing page
    $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";   
    if($actual_link !== SITE_URL."$url") 
        return false;    
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
        return false;      
    if(!isset($_SESSION[$form.'_token']))
        return false;
    if(!isset($_POST['_token']))
        return false;
    if($_SESSION[$form.'_token'] !== $_POST['_token'])
        return false;

    return true;
}

Now If I have one form in one page then it's validating the form successfully. 现在,如果我在一页中有一个表单,那么它将成功验证表单。

BUT in my website I have a page called create-menu.php Here I am using 4 form So this 4 form will generate 4 unique form token and I am use following input field to every 4 form : 但是在我的网站上,我有一个名为create-menu.php的页面。在这里,我使用的是4个表单,因此这4个表单将生成4个唯一的表单标记,并且我将以下输入字段用于每4个表单:

<input type="hidden" name="_token" value="<?php echo generate_Form_Token('menu_creation'); ?>">

But the problem is when I validating the form (Using Ajax) in process.php page. 但是问题是当我在process.php页面中验证表单(使用Ajax)时。 In this page only 1st form is validating but other 3 form is showing me error message (my custom error message if the form token is not match with session). 在此页面中,只有第一种形式正在验证,而其他三种形式正在向我显示错误消息(如果表单令牌与会话不匹配,则会显示我的自定义错误消息)。

process.php page process.php页面

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(verifyForm('menu_creation','menu-creation')) {
    // my code.....
    }
}

How can I solved this type of issue ? 我该如何解决这类问题? Can anyone assist me with that ? 有人可以协助我吗? Thank You. 谢谢。

Call the function that generates the token once . 调用一次生成令牌的函数。 Store the return value in a variable. 将返回值存储在变量中。 Use that variable in each form. 在每种形式中使用该变量。

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

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