2017-10-04 9 views
1

自分で作成したテンプレートを作成するときにノンスを使用するプロセスを理解しています。 しかし、データをプルするためにWordpress REST APIのみを使用するReactJS Appを開発しています。そのため、ユーザーはindex.phpにアクセスすることはありませんが、WP Rest APIへのAjaxコールはありません。Wordpress Auth + Nonces + Ajax + No Templating - クッキーノンスが無効

今、ノンスの仕事はできません。

register_rest_route('frontend', '/customer/', array(
    'methods' => 'GET', 
    'callback' => 'get_customer' 
)); 

register_rest_route('frontend', '/customer/', array(
    'methods' => 'POST', 
    'callback' => 'create_user_and_login' 
)); 

これらは私の関数です:

function get_customer() 
{ 
    return get_current_user_id(); 
} 


function create_user_and_login(){ 
    // dummy data for testing 
    $credentials = ['user_login' => '[email protected]', 'user_password' => 'XXXX', 'remember' => true]; 

    // create a new user/customer via woocommerce 
    $customerId = wc_create_new_customer($credentials['user_login'], $credentials['user_login'], $credentials['user_password']); 
    if(is_a($customerId,'WP_Error')) { 
     return $customerId; 
    } 
    // get the user & log in 
    $user = get_user_by('id', $customerId); 
    if($user) { 
     wp_set_current_user($customerId); 
     wp_set_auth_cookie($customerId); 
    } 
    // create new nonce and return it 
    $my_nonce = wp_create_nonce('wp_rest'); 
    return $my_nonce; 
} 

私は今create_user_and_login()をトリガー/customerにPOSTを実行する場合

は、私は次のエンドポイントを追加しました: これは私がこれまでにやっていることです新たに作成されたnonceがajaxレスポンスに返されます。その後、私は私の次のリクエスト、 /customer?_wpnonce=MY-NONCEにGETを実行するために、返されたnonceを使用しますが、私はエラーを取得:

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

私はthe nonce documentationをチェックするが、私は私の問題の解決策を見つけることができませんでした。セッションが同期していない可能性がありますか? Nonceが間違ったセッションで作成されるか、wp_set_auth_cookiewp_set_current_userが正しく呼び出されないようにするには?またはwp_localize_script機能を使用する必要がありますか?私はReactJSとWordpressバックエンドを分離したいので、これは問題になるでしょう。

POSTの後に2つのCookieがあり、wordpressのCookieとwordpress_logged_inのCookieがあります。

私には何が欠けていますか?

答えて

1

Check this answer

あなたがwp_set_auth_cookiewp_set_current_userを呼び出す場合でも、あなたは$my_nonce = wp_create_nonce('wp_rest');を呼び出すときナンスが古いセッションクッキーを使用して作成されているようです。しかし、次のリクエストでセッションが更新されます。つまり、ノンスが間違っています。

の答えのように、クッキーの更新を強制するには、次のフック(例えばのfunctions.php)を追加します。

 function my_update_cookie($logged_in_cookie){ 
      $_COOKIE[LOGGED_IN_COOKIE] = $logged_in_cookie; 
     } 
     add_action('set_logged_in_cookie', 'my_update_cookie'); 
+1

おかげでたくさん!それは動作します。 – Dario

関連する問題