【发布时间】:2020-10-28 06:44:01
【问题描述】:
这是我的问题。
实际上,我似乎是在尝试解决错误而不是解决问题,这就是为什么:
我正在创建一个在 WordPress 环境中运行良好的插件,并且我使用 WordPress nonce 作为身份验证模式。
我正在使用 jQuery/Ajax 在我之前使用 PHP 创建的标头中传递随机数:
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' );
},
),
) );
现在,如果我尝试使用 Postman、Visual Studio 代码(带有 REST 客户端的扩展名)或只是在我的 chrome 上的 URL 中使用 nonce(我在浏览器上控制台登录)运行相同的代码,它是不工作,例如:
邮递员:
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)。
如果我在我的 GET 请求中添加任何标头,Visual Studio 代码也会出现同样的问题,例如:
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
}
}
有什么提示吗?
【问题讨论】:
标签: php wordpress rest postman wordpress-rest-api