JavaScript-Mobile Form submission page, if the form form is submitted two times when the network is slow

Source: Internet
Author: User
Tags sha1 throw exception csrf attack
Mobile Site Submission page, the network good Time Normal, the network slow when the mobile phone page will always be loaded state, but fiddler Crawl has two times the same content of the submission, how to avoid this situation?

Reply content:

Mobile Site Submission page, the network good Time Normal, the network slow when the mobile phone page will always be loaded state, but fiddler Crawl has two times the same content of the submission, how to avoid this situation?

My approach is to generate a token on the server, commit the token at the time of submission, this is the first authentication, the second verification is when the form is submitted
Set the Submit button to disabled, usually a second validation is OK

// 提交表单数据到后台处理$.ajax({    type: "post",    data: studentInfo,    contentType: "application/json",    url: "/Home/Submit",    beforeSend: function () {        // 禁用按钮防止重复提交        $("#submit").attr({ disabled: "disabled" });    },    success: function (data) {        if (data == "Success") {            //清空输入框            clearBox();        }    },    complete: function () {        $("#submit").removeAttr("disabled");    },    error: function (data) {        console.info("error: " + data.responseText);    }});

CSRF Validation Class


  Getrequest ()->ispost ()) {//|        // |            try {//|            # #验证TOKEN//| Nocsrf::check (' Csrf_token ', $_post, True, 60*10, false);            60*10 for 10 minutes (null for no Authentication time)//| $result = ' CSRF check passed. Form parsed. ';            / |            $this->getrequest ()->getpost (' field ');//|       echo $result;        // |            } catch (Exception $e) {//| echo $e->getmessage (). ' Form ignored. ';        // |    }      // |        } else {//|        #生成TOKEN//|        $token = nocsrf::generate (' Csrf_token ');//|        $this->getview ()->assign (' token ', $token);//|    $this->getview ()->display (' page ');//|    }// | Front-end//|+----------------------------------------------------------------------class nocsrf{protected static $    Doorigincheck = false;      /** * Check CSRF tokens match between session and $origin.     * Make sure generated a tokens in the form before checking it.     * * @param String $key the session and $origin key where to find the token.     * @param Mixed $origin the object/associative array to retreive the token data from (usually $_post).     * @param Boolean $throwException (facultative) TRUE to throw exception on check fail, false or default to return FALSE. * @param Integer $timespan (facultative) makes the token expire after $timespan seconds. (NULL = never) * @param Boolean $multiple (facultative) makes the token reusable and not one-time.     (Useful for Ajax-heavy requests).     * * @return Boolean Returns FALSE If a CSRF attack is detected, TRUE otherwise. */public static function check ($key, $origin, $throwException =false, $timespan =null, $mulTiple=false) {$session = Session::getinstance (); if (! $session->has (' csrf_ '. $key)) if ($throwException) throw new \exception (' Missing CS            RF session token. ');                    else return false; if (!isset ($origin [$key])) if ($throwException) throw new \exception (' Missing CSRF form to            Ken. ');        else return false;                Get valid token from session $hash = $session->get (' csrf_ '. $key);        Free up session token for one-time CSRF token usage.        if (! $multiple) $session->forget (' csrf_ '. $key); Origin checks if (self:: $doOriginCheck && SHA1 ($_server[' REMOTE_ADDR '). $_server[' Http_user_agent ']  ! = substr (Base64_decode ($hash), ten, +)) {if ($throwException) throw new \exception (            ' Form origin does not match token origin. ');      Else          return false; }//Check If session token matches form token if ($origin [$key]! = $hash) if ($throwE            xception) throw new \exception (' Invalid CSRF token. ');        else return false; Check for token expiration if ($timespan! = null && is_int ($timespan) && intval (substr (base 64_decode ($hash), 0,) + $timespan < time ()) if ($throwException) throw new \exception            (' CSRF token has expired. ');        else return false;    return true;     }/** * Adds extra useragent and remote_addr checks to CSRF protections.    */public static function Enableorigincheck () {self:: $doOriginCheck = true; }/** * CSRF token generation method.     After generating the token, put it inside a hidden form field named $key. * * @param String $key The session key where the token would be stored. (would Also be the name of the hidden field name) * @return String the generated, Base64 encoded token.        */public static function generate ($key) {$session = Session::getinstance (); $extra = self:: $doOriginCheck?        SHA1 ($_server[' REMOTE_ADDR '). $_server[' Http_user_agent ']): '; Token generation (basically base64_encode any random complex string, time () was used for token expiration) $toke        n = Base64_encode (Time (). $extra. Self::randomstring (32));        Store the one-time token in session $session->put (' csrf_ '. $key, $token);    return $token;     }/** * Generates a random string of given $length.     * * @param Integer $length the string length.     * @return string the randomly generated string. */protected static function RandomString ($length) {$seed = ' abcdefghijklmnopqrstuvwxyzabcdefghijqlmnopqrt        suvwxyz0123456789 ';        $max = strlen ($seed)-1;        $string = "; for ($i = 0; $i < $length;        + + $i) $string. = $seed {intval (Mt_rand (0.0, $max))};    return $string; }}?>

must be clicked once, submitted once, it is impossible because the network is slow to appear you point to commit two times-the event triggered, how can it be like the water without root? If that's the case, it must be your code problem.

Well, there's no need to be that complicated.

You see the next two requests header , is not the first request down, exclusion is not 两次点击 caused (if the click caused, click to disable the DOM element click event), or is 代码部分原因 caused.

Incidentally, you 请求的代码 and Fiddler the captured data.

There are generally two reasons for submitting two times:
One, click the event triggered two times (this situation does not point to speed)
This is due to some JS plug-in caused by the need for Google to deal with, the more common is to iscroll.js cause the event to execute two times, there are many programs online.
Second, the Internet is busy, users can't wait, multiple clicks
Be sure to ajax drop the button before it is ready, if the disabled form can be submitted more than once, ajax then disabled remove it.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.