I am extending the WordPress REST api, registering a route, and pretends to make it secure.

The endpoint should be acessible only by logged users, but I didn't found something specific for that in REST api. So, I got to use nonce.

I register a javascript with a nonce variable, created by wp_create_nonce('abc1234'), and send it through ajax, in this way:

      url: resturi,
      data: {
        'nonce': nonce
      success: function(result) {
      error: function() {
        alert('Request level error');

And in the route, I catch the nonce in the following manner:

public function helloworld(\WP_REST_Request $request)
    if (!wp_verify_nonce($request["nonce"], "abc1234")) {
        return 'I got problems!';
    return 'Yes! You did it!';

What I think that is strange is that it works only when I am not logged. I read the source, and checked that it do considerations in case the user is logged in. I didn't understood the reason, but anyway, the point is that I don't know how to deal with it.

I could just remove the condition negation from helloworld method, but the things will got even more weird than it already got!

I wonders that I am securing my rest in the wrong way. So, what would be the right way to do so?

And yes, I tried to send the nonce with the ajax code:

  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', nonce );

but got a 403, with no clue why.

  • and how do you generate nonce? – Mark Kaplun Nov 7 '17 at 5:23
  • Used the wp_create_nonce('abc1234') sentence and sended it by wp_localize_script to be called by ajax in the assyncronous calling. – danilocgsilva Nov 7 '17 at 10:11
  • when a user is connected, the nonce hashing use the user identifier and the session token. after that, in the REST request, there is no autentification then the hash is different and the nonce verification failed. If you want to restrain the REST request to a logged in user, sent the session token to the request. look the functions wp_get_session_token to read the token and wp_validate_auth_cookie to learn how to check the token in the request. – mmm Nov 7 '17 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.