在Postman上使用Wordpress Nonce作为setRequestHeader,就像在jQuery/Javas



这是我的问题。

事实上,我似乎在试图解决一个错误,而不是解决一个问题,这就是为什么:

我正在创建一个在WordPress环境中运行良好的插件,我正在使用WordPress nonce作为身份验证模式。

我使用jQuery/Ajax来传递我以前用PHP:创建的头中的nonce

PHP:

wp_register_script('front-main', plugins_url('js/front-main.js' , __FILE__ ), '', '', true );
wp_enqueue_script('front-main');
wp_localize_script( 'front-main', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );

Javascript/jQuery:

$.ajax({
method: 'GET',
url: wpApiSettings.root+'top-list-route/my-top-list-get',
contentType: 'application/json; charset=utf-8',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
dataType: 'json',
success: ajaxResponse
});
function ajaxResponse(data) {
console.log(data)
}

到目前为止,很好,简而言之,这个应用程序将在我之前用PHP创建的路线上工作:

public function my_register_route() {
register_rest_route( 'top-list-route', 'my-top-list-get', array(
array(
'methods'  => WP_REST_Server::READABLE,
'callback' => array($this, 'my_top_list_get'),
'permission_callback' => function() {
return current_user_can( 'edit_posts' );
},
),
) );

现在,如果我试图用nonce(我在浏览器上控制台.log(、Postman、visualstudio代码(带有REST客户端的扩展(或只是在chrome上的URL中运行相同的代码,它将不起作用,例如:

邮递员:

GET http://netzstrategen.local/wp-json/top-list-route/my-top-list-get
(IN THE HEADERS section) X-WP-Nonce (key) 47489127d8 (value, for example)

将返回:

{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}

或者如果我使用这个URL,例如:

http://netzstrategen.local/wp-json/top-list-route/my-top-list-get?_wpnonce=47489127d8

它将返回相同的状态(403 rest_cookie_invalid_nonce(。

visual studio代码也有同样的问题,如果我在GET请求中添加任何标头,例如:

GET http://netzstrategen.local/wp-json/top-list-route/my-top-list-get?_wpnonce=47489127d8

将返回:

HTTP/1.1 403 Forbidden
{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}

有什么提示吗?

这可能有点晚,但有望达到其他人可能需要的分辨率,这就是我在函数中传递nonce的方式。php

wp_localize_script( 'app', 'WP_API_Settings', array(
'endpoint' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );

在Postman中,我通过请求头传递nonce

X-WP-Nonce:{{nonce}}
Cookie:{{cookie}}

我注意到nonce过期了,您必须将新值传递给Postman。我正在使用一个变量,以便它应用于集合中的所有路由。如果您得到一个无效的nonce,请确保您是通过Web登录的,使用Chrome Developer Tools,F12,并在控制台中键入wpApiSettings.noce,它显示最新的nonce值。将该值复制并粘贴到变量中,或者使用原始值并应用于标头。

我希望这能有所帮助,弄清楚它真是太痛苦了!

最新更新