• Resolved antonop4u

    (@antonop4u)


    Hi I’m trying to get the “current user ID” inside a REST API custom root.

    reading the documentation I believe that there is a “nonce” authentication involved.

    I don’t know I to do the nonce verification using the getJSON() jQuery function.

    Here below is the code I wrote so far:

    as fist I pass the nonce to JavaScript using:

    
    wp_localize_script( 'rm_search_js', 'live_reserch', array(
    	'ajaxurl' => admin_url( 'admin-ajax.php' ),
    	'root_url' =>	get_site_url(),
    	'nonce' => wp_create_nonce( 'wp_rest' )
    ) );
    

    then I set the nonce inside the jquery function,

    
    jQuery.getJSON( live_reserch.root_url + '/wp-json/rm/research/v1/search?' + "/* rmSearchParameters */" + '&_wpnonce=' + live_reserch.nonce, data => {
    
    	// do something with the data
    
    }
    

    on the php side I register a new root

    
    function rm_custom_rest_research(){
    	
    	register_rest_route( 'rm/research/v1', 'search', array( 	
    		'methods'	=>	WP_REST_SERVER::READABLE, 
    		'callback'	=> 	'rm_search_results'
    	)	);
    }
    add_action( 'rest_api_init', 'rm_custom_rest_research' );
    

    and finally I set the function managing the new rest API root

    
    function rm_search_results( $data ) { 
    
    	$nonce = $data['_wpnonce'];
    
    	//verify the nonce and get the current user id.
    
    	$user_id = get_current_user_id();
    
    	// do something with the $user_id
    
    }
    

    Does anyone knows how can I do the verification and get the current user id?

    Thanks in advance.

Viewing 8 replies - 1 through 8 (of 8 total)
  • Moderator bcworkz

    (@bcworkz)

    Client script does not need to verify the nonce. The purpose of the nonce is for server side script to confirm the data received actually came from the client the server is interacting with and not from some third party attacker. In any case, client script does not typically have enough information to verify the nonce, it in part involves the secret salts defined in wp-config.php.

    The client app should typically know the current user, at least by login name, since it generally initiates authentication. Other user information can be had from the /users route.

    In any case, one could create custom routes/endpoints to accomplish those tasks server side and respond with the results.

    Thread Starter antonop4u

    (@antonop4u)

    Hi bcworkz

    sorry I probably didn’t explain my problem correctly.
    The function, where I’m trying to retrieve the user id, is on the server side.
    is the php callback function that defines what data the custom JSON url will return.
    In any other circumstance (on the server side) the function

    
    <?php
    
    $user_id = get_current_user_id();
    
    ?>
    

    will provide the id of the current logged in user, inside this particular function, it always returns 0.

    So there is no way for me to verify if the data the custom url returns are propriety of the current user.

    I read on the forum and on the documentation that to be able to verify te current user id inside this php function, the function itself must first verify the “nonce” from the client.

    I’ve tried to use the wordpress-php function

    
    wp_verify_nonce(  $nonce )
    
    

    but I still cant get the “current user id” on the server side.

    any idea?

    • This reply was modified 5 years, 1 month ago by antonop4u.
    • This reply was modified 5 years, 1 month ago by antonop4u.
    Thread Starter antonop4u

    (@antonop4u)

    Hi bcworkz,

    it seems that I was able to solve the problem using the “check_ajax_referer” function :

    Now that I can check if the data I’m about to return in the custom JSON url belong to the current user, I have a new question, I read that using the “nonce” is not considered safe, here below I pasted the code I’m using:

    
    if( check_ajax_referer('wp_rest', '_wpnonce') ){
    	$current_user = get_current_user_id();
    }else{
    	$current_user = 0;
    }
    // I get post owner id
    $document_customer = (int) get_post_meta( $id, 'rm_customer' )[0];
    
    // I check if the post belongs to the current user
    if(document_customer == current_user ){
       // return the data
    }else{
       // return nothing
    }
    

    Is it in your opinion safe to use the nonce in this way?

    Moderator bcworkz

    (@bcworkz)

    Ah, that makes much more sense. Thanks for clarifying. I recall someone else a little while back having the same current user issue, but I don’t remember how they resolved it. I’m glad that checking Ajax referrer works for you, though it’s not clear to me how it would impact getting the current user ID. The function checks the nonce, which serves to confirm the Ajax request came from the same user that loaded the calling script. That user could have ID == 0 and the check will still succeed. But if it’s working for you, who am I to argue? ??

    Anyway, I think your code snippet is marginally OK as far as verifying the nonce goes, provided that the value in post meta can never be 0. To be extra safe, it would be better to explicitly fail the request right then and there when the referrer check fails instead of setting $current_user to 0. An easy way to do that is to pass a third true argument to the check function so that it immediately dies on check failure, though that can cause issues on the calling end if no response comes back. Ideally, an error response should be sent and handled appropriately client side.

    Out of curiosity, in what way is a nonce not considered safe? Can you easily provide a reference for that? (don’t try too hard to find one, it’s not that important) It certainly is not a complete security solution in itself, it’s part of a multi-faceted security model. Additionally, a WP nonce is not a true nonce as it can be used multiple times in a 24 hour period. Other than that, it does what it’s supposed to do, confirm a request comes from a page previously served to the same user. Nothing more.

    Thread Starter antonop4u

    (@antonop4u)

    Thanks for the suggestions, I’ll implement them in my code.

    I read in the forum of a similar problem, he was trying to check if the user can do something, but I found his solution not really clear, he also said that he wasn’t sure it was the best solution.

    my problem in my opinion is different, because I’m not trying to check if the user has a specific capability, but I want to be sure of it’s “identity”, and return to him posts that are meant to be shown only to him.

    What do you mean when you say “That user could have ID == 0 and the check will still succeed”? I though that the user id could only be $id >= 1 where 1 is the admin id.

    My concern about the nonce safety is because of this sentence:

    ” Nonces should never be relied on for authentication or authorization, access control. Protect your functions using current_user_can(), always assume Nonces can be compromised. ”

    that I found written several times in the official documentation like for example in this page:

    what do you think?

    Moderator bcworkz

    (@bcworkz)

    Though you are not interested in capability, the fact API callbacks get the current user ID as 0 is rooted in the same issue. We cannot get a capability on a user 0, nor can we verify the user’s identity with such an ID.

    If one is not logged in, the current user ID comes back as 0. Code still generates a nonce for user 0. If you do wp_verify_nonce() (called by the Ajax referrer check), the nonce validates for that same user 0, assuming other criteria like the time period are valid.

    Nonces do not validate users. That is correct. Nonces confirm the submitted data came from a page recently served to that same user (all non-logged-in users are the same “user” in this context). Users are validated by verifying their login credentials or because their browser sent a valid auth cookie. Two different, though related functions. If WP gives us a non-zero user ID, the user has been validated. To counter a possible cross site request forgery (CSRF) attack, both should be verified before sending out sensitive data.

    Almost anything from a browser or app can be spoofed. It’s much easier for an attacker to get a valid nonce than it is to spoof a valid auth cookie.

    Thread Starter antonop4u

    (@antonop4u)

    I believe it’s clear now; hopefully… ??
    bcworkz thank you very much for your help.

    Moderator bcworkz

    (@bcworkz)

    You’re welcome.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘how to verify wp nonce using getJSON()’ is closed to new replies.