questions

Using nonce in custom WordPress API end-point

Rate this post

I’m trying to write an plugin that allows a WordPress authenticated user to access Firebase. I’d like a Javascript app that is delivered from Firebase hosting to make an API request to WordPress and get back a signed JWT.

Since I want to use the authenticated user, I figure I’ll need to send a nonce with the API request. In order to test that I’ve got the following code Plugin code:

function my_awesome_func($data) {
  $uid = $data['id'];
  // var_dump($data);  
  var_dump(wp_create_nonce( 'wp_rest' ));
  var_dump(get_current_user_id());
  return $uid;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

The idea being – the first time I hit the end-point it returns the nonce. I’ll then append it to the URL and try again, hopefully getting the current user details the second time around. http://localhost/wp-json/telomere/firebase_jwt/v1/user/1234?_wpnonce=<nonce>

All I get back is {"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

How do I fix this code so that it provides and accepts a nonce?

Thanks.

✔️Solution:

The problem was my misunderstanding of how a nonce was created (despite the docs being excellent).

https://developer.wordpress.org/reference/functions/wp_create_nonce/ states that it uses the user’s UID in the generation of the nonce, but when I first called the custom API end-point the user was presenting as unauthenticated. The nonce then created didn’t verify.

Instead, I copied the Hello Dolly code and output an authenticated nonce on the admin page and then used that in my test API call.

FWIW, it looks like this

function my_awesome_func($data) {
  $uid = $data['id'];
  return $uid;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );


function output_nonce() {
  $nonce = wp_create_nonce('wp_rest');
    printf('nonce %s', $nonce);
}


add_action( 'admin_notices', 'output_nonce' );

Leave a Reply

Your email address will not be published.

Back to top button