2017-10-04 13 views
1

나만의 템플릿을 만들 때 넌센스를 사용하는 과정을 알고 있습니다. 하지만 데이터를 가져 오는 데 Wordpress REST API 만 사용하는 ReactJS 앱을 개발 중이므로 사용자는 index.php에 액세스 할 수 없지만 WP Rest API에 대한 Ajax 호출은 수행하지 않습니다.Wordpress Auth + Nonces + Ajax + No Templating - 쿠키 넌스가 올바르지 않습니다.

이제 nonce를 사용할 수 없습니다.

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을 실행하기 위해 반환 넌스를 사용하지만, 나는 오류 얻을 : 나는 the nonce documentation을 확인

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

을하지만 내 문제에 대한 해결책을 찾을 수 없습니다. 세션이 동기화되지 않았을 수 있습니까? Nonce가 잘못된 세션에서 생성되거나 wp_set_auth_cookiewp_set_current_user이 올바르게 호출되지 않도록하려면? 아니면 wp_localize_script 함수를 사용해야합니까? ReactJS와 Wordpress 백엔드를 분리시키려는 경우 문제가 될 것입니다.

POST 후 쿠키가 두 개 있는데, wordpress 쿠키와 wordpress_logged_in 쿠키입니다.

무엇이 누락 되었습니까?

답변

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