Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to submit data from form containing code to avoid csrf attacks using php

I am trying to pass data in a form that has code that checks for csrf attacks first and then sends dat using php, but the code always tells me that there is an attack even though there is not attack The code always just executes the error message and the rest of the code is not considered.

php code:

    <?php 
$csrf_avoid= bin2hex(random_bytes(20));
 $_SESSION['auth_token'] = $csrf_avoid;                   
if (isset($_POST["save_entry"])) {
                             
if ($_POST["auth_token"] !== $csrf_avoid) {
// show an error message
echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
                          // return 405 http status code
 exit();
  }
 else{                                                
// do anything here there is no csrf attacks                                                
 }                  
 }              
?>

html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<input type="hidden" name="auth_token" value="<?php echo $csrf_avoid;?>">

>Solution :

first of, don’t generate a token every time, and check the session when submitting :

if(!isset($_SESSION['auth_token'])) {
    $csrf_avoid = bin2hex(random_bytes(20));
    $_SESSION['auth_token'] = $csrf_avoid;     
}
                
if (isset($_POST["save_entry"])) {
    //check the session                          
    if ($_SESSION['auth_token'] !== $csrf_avoid) {
        // show an error message
        echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
        // return 405 http status code
        exit();
    }
    else {                                                
        // do anything here there is no csrf attacks

        // you could regenerate token on submit, so the current one becomes invalid
        $csrf_avoid = bin2hex(random_bytes(20));
        $_SESSION['auth_token'] = $csrf_avoid;                                                  
    }                  
}

Also change your input to :

<input type="hidden" name="auth_token" value="<?php echo $_SESSION['auth_token'];?>">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading