• Resolved kimaldis

    (@kimaldis)


    I have a rest endpoint, called from an admin settings page. When I check for a logged in user in the endpoint there’s nobody there. Is this correct, am I going to have to pass over a user’s name & password?

    thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Requests to the REST API will be handled as a logged-out user unless your request is accompanied by a nonce. From the documentation:

    For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header.

    You’d first create the nonce and pass it to the script with wp_localize_script():

    wp_localize_script( 'my-script', 'MyScript', array(
    	'nonce' => wp_create_nonce( 'wp_rest' ),
    ) );
    

    Then, when using jQuery for a request, you set the X-WP-Nonce header to the nonce value:

    jQuery.ajax( {
    	url: url,
    	data: data,
    	beforeSend: function( request ) {
    		request.setRequestHeader( 'X-WP-Nonce', MyScript.nonce );
    	},
    } )
    
    Thread Starter kimaldis

    (@kimaldis)

    That’s why. Perfect, many thanks.

    Thread Starter kimaldis

    (@kimaldis)

    Hmm .. maybe not. I have the nonce passed over, it appears in the headers in the endpoint but still I have no logged in users. Any other thoughts?

    thanks.

    Thread Starter kimaldis

    (@kimaldis)

    Never mind. I was doing something so incredibly stupid I’d rather not talk about it.

    Sorry for the noise, thanks for your help, problem solved.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Rest endpoints, user logged in’ is closed to new replies.