我目前正在开发一个基于新Wordpress Rest API的多步骤注册系统,我遇到了一个与nonce生成和验证相关的问题。
我的第一步是从前端表单向用户询问基本信息(name-firstname-电子邮件地址)。第二个是向他询问其他元数据信息。然后第三个向他询问密码和密码确认。
该过程中有3个不同的HTTP Post请求,所有内容都在AJAX中处理。我应用的策略是,如果第一篇帖子正常,则在服务器端生成nonce,并在JSON响应中返回它。以下是第一步创建用户的代码:
$user_id = wp_insert_user( $userdata ) ;
$user = new \\WP_User($user_id);
if (!empty( $user ) && $user instanceof \\WP_User) {
$user->add_role( \'subscriber\' );
}
// Autologin after registration
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
// Storing the regitration event for the user
$this->saveLoginEvent( $user_id );
$data = array(
\'user_id\' => $user_id,
\'nonce\' => wp_create_nonce( \'wp_rest\' ),
\'message\' => \'user_created\'
);
用户已正确创建并登录。但是,在附加步骤中使用此nonce被认为是无效的(总是得到403)。我的临时代码如下:
/**
* authenticate_call - Default permission callback used to validate that the call is coming from our frontend
*
* @return {WP_nonce} The state of the nonce, if it is verified or not
*/
public function authenticate_call() {
if ( isset( $_REQUEST[\'_wpnonce\'] ) ) {
$nonce = $_REQUEST[\'_wpnonce\'];
} elseif ( isset( $_SERVER[\'HTTP_X_WP_NONCE\'] ) ) {
$nonce = $_SERVER[\'HTTP_X_WP_NONCE\'];
}
if ( empty( $nonce ) || null === $nonce ) {
// No nonce at all, so act as if it\'s an unauthenticated request.
return new \\WP_Error( \'rest_cookie_no_nonce\', __( \'Nonce is invalid\' ), array( \'status\' => 403 ) );
}
$result = wp_verify_nonce( $nonce, \'wp_rest\' );
if ( ! $result ) {
return new \\WP_Error( \'rest_cookie_invalid_nonce\', __( \'Cookie nonce is invalid\' ), array( \'status\' => 403 ) );
}
return true;
}
我遇到的错误是第二个:
rest_cookie_invalid_nonce. nonce作为URL参数传递,如下所示
POST www/api/url?_wpnonce=a30e88f0bd. 有什么想法吗?您知道后端无法生成nonce并将其返回到前端吗?我应该在前端使用一种我还不知道的方法生成它吗。如果有帮助,我将使用木材和细枝作为前端建筑组件。
提前感谢,