在自定义 Wordpress API 端点中使用随机数

Using nonce in custom Wordpress API end-point

我正在尝试编写一个允许经过 Wordpress 身份验证的用户访问 Firebase 的插件。我想要一个从 Firebase 托管提供的 Javascript 应用程序向 Wordpress 发出 API 请求并取回签名的 JWT。

因为我想使用经过身份验证的用户,我认为我需要在 API 请求中发送随机数。为了测试我有以下代码插件代码:

function my_awesome_func($data) {
  $uid = $data['id'];
  // var_dump($data);  
  var_dump(wp_create_nonce( 'wp_rest' ));
  var_dump(get_current_user_id());
  return $uid;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

我的想法是——我第一次到达终点时 returns 随机数。然后我会将其附加到 URL 并重试,希望第二次获得当前用户的详细信息。 http://localhost/wp-json/telomere/firebase_jwt/v1/user/1234?_wpnonce=<nonce>

我得到的只是 {"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

如何修复此代码,使其提供和接受随机数?

谢谢,

您在服务器响应区域中使用了 wp_create_nonce - 这是错误的。那是 wp_verify_nonce 的地方。 您需要在客户端创建 wp_create_nonce。

例如:

jQuery.ajax( {
        url: "YOUR_API_URL?api_nonce=<?php echo wp_create_nonce("wp-rest"); ?>",
        method: 'GET'
    } ).done( function ( response ) {
});

然后在回调函数里面验证一下

function my_awesome_func($data) {
  var_dump(wp_verify_nonce( $_GET["api_nonce"], 'wp-rest' ) );
  return $uid;
}

或者最好使用 API 授权的官方指南:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

问题是我误解了 nonce 是如何创建的(尽管文档非常好)。

https://developer.wordpress.org/reference/functions/wp_create_nonce/ 声明它在随机数的生成中使用用户的 UID,但是当我第一次调用自定义 API 端点时,用户显示为未经身份验证。然后创建的随机数没有验证。

相反,我复制了 Hello Dolly 代码并在管理页面上输出了经过身份验证的随机数,然后在我的测试 API 调用中使用了它。

FWIW,看起来像这样

function my_awesome_func($data) {
  $uid = $data['id'];
  return $uid;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );


function output_nonce() {
  $nonce = wp_create_nonce('wp_rest');
    printf('nonce %s', $nonce);
}


add_action( 'admin_notices', 'output_nonce' );