官术网_书友最值得收藏!

Time for action – Add a security nonce

  1. Open the wp-live-blogroll.js.php file and add create a nonce at the beginning of the script:
      function WPLiveRoll_ScriptsAction() 
            {
              global $wp_live_blogroll_plugin_url;
              if (!is_admin())
              {
                // create a nonce
                $nonce = wp_create_nonce('wp-live-blogroll');
    
                wp_enqueue_script('jquery');
                wp_enqueue_script('wp_live_roll_script', 
                $wp_live_blogroll_plugin_url.'/wp-live-blogroll.js', 
                array('jquery'));
            
              }
            }
  2. Modify the Ajax call to include the generated nonce as an additional parameter:
       $.ajax({
          type: "GET",
          url: LiverollSettings.plugin_url + '/wp-live-blogroll-ajax.php',
          timeout: 3000,                    
          data: {
             link_url: this.href,
     _ajax_nonce: '<?php echo $nonce; ?>'
           },       
           success: function(msg) {
  3. Modify wp-live-blogroll-ajax.php and add this check at the beginning of Ajax handler function:
           function WPLiveRoll_Handle ajax($link_url)
            {
                // check security
                check_ajax_referer( "wp-live-blogroll" );

With this simple modification, we have made sure that our Ajax handling script is used only when our plugin calls it.

What just happened?

When our script is run the next time, a unique nonce is created using the wp_create_nonce() function. We use a nonce identifier as a parameter:

    $nonce = wp_create_nonce( 'wp-live-blogroll' );

We then pass this nonce as the Ajax_nonce parameter. WordPress checks this parameter automatically in the check_ajax_referer function, which also uses the nonce identifier parameter:

        check_ajax_referer( "wp-live-blogroll" );

If the check fails, the script will simply exit at that point (internally, die(-1) happens).

Note

Quick reference

wp_create_nonce(nonce_id): It creates a unique nonce using the identifier.

check_ajax_referer(nonce_id): It is used to check Ajax nonces; passed as the ajax_nonce parameter, using the nonce identifier.

To read more about possible security implication and Cross-Site Request Forgery (CSRF), visit http://en.wikipedia.org/wiki/Cross-site_request_forgery.

主站蜘蛛池模板: 阜阳市| 临桂县| 滦平县| 永兴县| 龙海市| 凤城市| 佛教| 白朗县| 和静县| 台江县| 桑植县| 铜山县| 临潭县| 乐业县| 丹阳市| 揭阳市| 阿图什市| 建水县| 乐清市| 丹寨县| 大厂| 南昌市| 望谟县| 卓尼县| 兴安盟| 威远县| 高阳县| 莲花县| 郑州市| 澄迈县| 裕民县| 保康县| 庆阳市| 和政县| 柞水县| 开远市| 沙坪坝区| 钟祥市| 龙南县| 朝阳区| 凤城市|