nonce token after ajax response and hash problems using ajax jquery type json

随声附和 提交于 2019-12-14 03:14:59

问题


i have login with my own code at php, now i dont so good at jquery ajax and so on, my login using ajax jquery type json , i take all vals and post them to server side php which check all details , and response answer via the same jquery ajax .

the problem is i added nonce token that maded in php to the login form and every time after user try to login the nonce change , the problem is only when i refresh the login page the nonce changed to the good nonce else its will keep the same nonce token and will send with the post not the updated one because the ajax didnt refresh the page after login .

So the question is how i trigger the ajax to refresh the nonce token after every response ? the nonce token is write in php.

and more thing about the hash nonce token , its make that hash string sometime:

asdaskjn34kj+sdf/sd=

now the ajax jquery auto remove the '+' from the hash string so its send wrong token in the POST, here my hash function :

public static function RandomBytes($count, $printable=FALSE)
    {
        $bytes = '';

    // supress warnings when open_basedir restricts access to /dev/urand
        if(@is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE)
        {
            $bytes = fread($hRand, $count);
            fclose($hRand);
        }
    if((strlen($bytes) < $count) && function_exists('mcrypt_create_iv'))
    {
        // Use MCRYPT_RAND on Windows hosts with PHP < 5.3.7, otherwise use MCRYPT_DEV_URANDOM
        // (http://bugs.php.net/55169).
        if ((version_compare(PHP_VERSION, '5.3.7', '<') && strncasecmp(PHP_OS, 'WIN', 3) == 0))
          $bytes = mcrypt_create_iv($count, MCRYPT_RAND);
        else
          $bytes = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
    }
    if((strlen($bytes) < $count) && function_exists('openssl_random_pseudo_bytes'))  // OpenSSL slow on Win
    {
        $bytes = openssl_random_pseudo_bytes($count);
    }
    if ((strlen($bytes) < $count) && @class_exists('COM'))
    {
        // Officially deprecated in Windows 7
        // http://msdn.microsoft.com/en-us/library/aa388182%28v=vs.85%29.aspx
        try
        {
            $CAPI_Util = new COM('CAPICOM.Utilities.1');
            if(is_callable(array($CAPI_Util,'GetRandom')))
            {
                $bytes = $CAPI_Util->GetRandom(16,0);
                $bytes = base64_decode($bytes);
            }
        }
        catch (Exception $ex)
        {
        }
    }
        if (strlen($bytes) < $count)
        {
            // This fallback here based on phpass code
            $bytes = '';
            $random_state = microtime();
            if (function_exists('getmypid'))
                $random_state .= getmypid();

            for ($i = 0; $i < $count; $i += 16) {
                $random_state =
                    md5(microtime() . $random_state);
                $bytes .=
                    pack('H*', md5($random_state));
            }
            $bytes = substr($bytes, 0, $count);
        }

        if ($printable)
            return base64_encode($bytes);
        else
            return $bytes;
    }

any one know how to change this function to make the strings without '+' in the hashesh?


回答1:


To change hash function, if only '+' is the problem you may keep a check while creating the string,

next_char = Randomly-created-char;
if(next_char == '+'){
 //do nothing
} else{
 hash .= next_char;
}

Here is how the html and php files should be like.

The ajax call is shown in the .html file.

.php that loads your form for the first time.

<!DOCTYPE html>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
    $("#check").click(function(){
        $("#keyvalue").text($("#key").val());
    });
    $("#submit").click(function(){
    var text = $("#text").val();
    var key = $("#key").val();
        $.ajax({
            url: 'trial.php',
            data: {text: text, key:key},
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if(data.status == "fail"){
                    $("#status").html(data.message);
                }else{
                    $("#status").html(data.message);
                    $("#key").val(data.key);
                    $("#keyvalue").text('');
                }
            }
        });
        return false;
    });
 });
</script>
</head>
<body>
    <form method="post" action="trial.php" onsubmit="return send_form();">
        <input type="text" name="text" id="text"/>
        <input type="hidden" id="key" name="key" value="<?php echo $key?>"/> //Look here.
        <button id="submit">Send data and get new key</button>
    </form>
    <br><br>
    <div id="status"></div>
    <br><br>
    <button id="check">What's current value of key?</button> --------> <span id="keyvalue"></span>

    <div id="response"></div>
</body>

</html>

.php

<?php

//You get the form contents here.

$key = isset($_POST['key']) ? $_POST['key'] : "error";
$text = isset($_POST['text']) ? $_POST['text'] : "empty";

//Check them if it matches with DB's entry, if doesn't you set $key = "error";

if($key=="error"){
    $status = "fail";
    $message = "There was some error processing your form.";
    exit;
} else{

    //You generate another random key.
    $random ='';
    for ($i = 0; $i < 10; $i++) {
        $random .= chr(mt_rand(33, 126));
    }

    //Now here in steps save it to your DB. So that when next form is submitted you can match it.
    //And send back response to html file, where ajax will refresh the key.
    $status = "success";
    $message = "
    Your form was processed succesfully<br>
    The text you sent was ".$text.", and the key you sent was ".$key.".
    The new key sent to you can be seen by pressing the button below, has value, ".$random."<br><br>
    ";
    }

    echo json_encode(array("status" => $status, "message" => $message, "key" => $random));

?>

Hope this helps you.

While generating the form for the first time, you have to give the key and nonce without any ajax, the ajax function will be called when this following keys have been used.

echo "<input type='hidden' id='key' name='key' value='".$key."'>";

echo "<input type='hidden' id='nonce' name='nonce' value='".$nonce."'>";



回答2:


This was really useful as I had encountered the same problem - I had considered an auto page refresh for the login but this is a real inconvenience to the user - I also added a block so that the ip and/or user are blocked after 5 failed attempts



来源:https://stackoverflow.com/questions/17953223/nonce-token-after-ajax-response-and-hash-problems-using-ajax-jquery-type-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!