本文介绍了无法让Wordpress Nonce与Wp-Rest API应用程序一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该是安全的应用程序,因此使用Nonce,但我无法使它们正常工作.我尝试了几种方法,但是由于验证不起作用,显然缺少了一些东西.

I have an app which is should be secure and therefore using Nonce's but I can't get them to work.I have tried several options but apparently something is missing as the validation doesn't work.

我的js代码片段是:

function placeNew(next){
  _nonce = $('input#_nonce').val();
  request = $.ajax({
    type: 'POST',
    url: url_path + '/foo/v1/newbee',
    data: {bid : next , _nonce : _nonce},
    security: '<?php echo wp_create_nonce( "a" ); ?>',
    dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
  str = JSON.stringify(response);
  if(response["error"]){
    alert(response["message"]);
  }

使用以下代码将现时值添加到页面:

The nonce is added to the page with the following code:

$nonce = wp_create_nonce( 'a' );
echo "<input type='hidden' id='_nonce' value=" . $nonce ."/>";

在php中,以下函数片段用于获取和比较随机数:

Within php the following function fragment is used to get and compare the nonce:

function ace($request) {
    global $wpdb;
    $timestamp = time();
    $nonce = (string) $request['_nonce'];
    $verify = check_ajax_referer( 'a', $nonce, false );
    if ( ! $verify){
        $errMsg = $nonce . '-'. $verify .' not validated ';
        return (object) array(error => true, message => $errMsg);
    }

我总是收到未验证"消息. $ nonce有值,但$ verify永远不会有值.

I always do get the message "not validated". $nonce has a value but $verify never gets a value.

推荐答案

根据文档:

您缺少的重要部分是:

要使其正常工作,必须在wp_create_noncewp_rest中命名操作.

For it to work, you must name your action in the wp_create_nonce to wp_rest.

因此,对于您的代码,您必须更改以下所有实例:

So for your code, you must change all instances of:

wp_create_nonce( "a" )

wp_create_nonce( 'wp_rest' )

此外,如文档所述:

因此,将其添加到您的ajax很简单,看起来像这样:

So adding this to your ajax is simple and looks something like:

var _nonce = "<?php echo wp_create_nonce( 'wp_rest' ); ?>";
$.ajax({
    type: 'POST',
    url: url_path + '/foo/v1/newbee',
    data: {
        bid : next
    },
    dataType: 'json',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', _nonce );
    }
});

此外,要修复支票

check_ajax_referer( 'a', $nonce, false )

现在应该是

check_ajax_referer( 'wp_rest', '_nonce', false )

这篇关于无法让Wordpress Nonce与Wp-Rest API应用程序一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 11:32