wordpress中nonce使用记录

如下步骤:

注册nonce

wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );

查看html中的打印

<input type="hidden" id="myplugin_inner_custom_box_nonce" name="myplugin_inner_custom_box_nonce" value="6b83c7da39" />

获取nonce

$nonce = $_POST['myplugin_inner_custom_box_nonce'];

有效性判断

// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) ) {
     return ;
}

wp_nonce_field()方法官方说明:

wp_nonce_field( int|string $action = -1, string $name = '_wpnonce', bool $referer = true, bool $echo = true )

官方解释。

The nonce field is used to validate that the contents of the form came from the location on the current site and not somewhere else. The nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce field in forms.

The $action and $name are optional, but if you want to have better security, it is strongly suggested to set those two parameters. It is easier to just call the function without any parameters, because validation of the nonce doesn’t require any parameters, but since crackers know what the default is it won’t be difficult for them to find a way around your nonce and cause damage.

The input name will be whatever $name value you gave. The input value will be the nonce creation value.

然后我发现了另一个方法

$nonce = \wp_create_nonce('my_nonce_test');

查找一下官方

wp_create_nonce( string|int $action = -1 )
Creates a cryptographic token tied to a specific action, user, user session, and window of time.

简单看一下源码

function wp_create_nonce( $action = -1 ) {
        $user = wp_get_current_user();
        $uid  = (int) $user->ID;
        if ( ! $uid ) {
            /** This filter is documented in wp-includes/pluggable.php */
            $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
        }
        $token = wp_get_session_token();
        $i     = wp_nonce_tick();
        return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
    }

很明显,它和AWT的token生成意思差不多,就是uid,时间等生成的一个串。
而且我们看了验证nonce的函数。看一下

wp_verify_nonce( $nonce, $action = -1 )
1.Verifies that a correct security nonce was used with time limit.
2.A nonce is valid for 24 hours (by default).
第二点明确指出,默认的失效时间是24小时。说明了这个nonce就是一个有效期为24小时的token

好了,怎么理解呢?
1:创建nonce的时候,让我们提供一个 action,这个action其实就是一个token盐。我们可以为不同的操作添加不同的盐。
如,添加用户信息用一个盐,添加产品信息用一个盐。当我们去验证的时候,即:wp_verify_nonce ()调用验证时,我们把盐传入,验证,如果是用户添加盐,在产品信息里就直接返回了。当然这只是意淫出来的一个虚拟场景。听官方文档上看,它的用户要大的多。
所以,简单说:
nonce为我们的具体操作,生成一个默认24小时的token,此token只为某个action(动作,如保存用户信息起作用)。来保证表单安全。

我们只要使用 wp_nonce_field 就可以在html中输出input 的隐藏字段,或者我们使用 wp_create_nonce 创建一个nonce,通过ajax交给前端手动渲染或者使用。

接收到表单后,只需要wp_verify_nonce 即可验证nonce 的有效性。

暂无评论

相关推荐

微信扫一扫,分享到朋友圈

wordpress中nonce使用记录