在AJAX注册过程中处理随机数生成

时间:2016-09-01 作者:Balessan

我目前正在开发一个基于新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并将其返回到前端吗?我应该在前端使用一种我还不知道的方法生成它吗。如果有帮助,我将使用木材和细枝作为前端建筑组件。

提前感谢,

1 个回复
SO网友:Balessan

如果有人用它来扼杀,正确的解决方法是两者兼用wp_set_auth_cookie 指定第二个参数是logged\\u-in cookie,它现在为我提供以下代码:

wp_set_current_user($user_id);
if ( wp_validate_auth_cookie( \'\', \'logged_in\' ) != $user_id )
{
    wp_set_auth_cookie( $user_id );
}
并添加一个操作,如本线程中所建议的:Extend Wordpress (4.x) session and nonce 在不需要刷新页面的情况下,正确覆盖登录的当前cookie。

这肯定是一个棘手的问题,任何地方都没有记录在案。有人试过吗?

谢谢你的关注,