- WordPress Plugin Development Beginner's Guide
- Vladimir Prelovac
- 239字
- 2021-05-21 20:12:22
Time for action – Add a security nonce
- 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')); } }
- 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) {
- 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.
- Vue.js框架與Web前端開發(fā)從入門到精通
- Moldflow 2010完全自學與速查手冊(模流分析·成本控制)
- Django 1.2 E/commerce
- 中文版Photoshop CS6平面設計實用教程(第2版)
- Photoshop CS6中文版從入門到精通(核心技法卷):摳圖、修圖、Camera Raw、調(diào)色、銳化、合成
- iPhone Applications Tune/Up
- 3ds Max/MaxScript印象 腳本動畫制作基礎與應用
- Premiere Pro CC 2018基礎教程(第3版)
- 中文版After Effects CC 2018 動漫、影視特效后期合成秘技
- Premiere Pro短視頻剪輯零基礎一本通
- Adobe創(chuàng)意大學InDesign產(chǎn)品專家認證標準教材(CS6修訂版)
- Photoshop CS6平面設計實戰(zhàn)從入門到精通(經(jīng)典暢銷版)
- Python氣象應用編程
- Photoshop CS6淘寶美工完全實例教程(培訓教材版)
- Getting Started with Oracle Hyperion Planning 11