[How to] permission_callback on register_rest_route is showing user is not logged in
I struggled with this one a bit and thought it might help to create a post since this appears to be a common problem.
When I was building thesrest routes on OddsRabbit, the is_user_logged_in()
function is returning false
even when the user is logged in.
Example:
register_rest_route('wp/v1', '/your_endpoint', [
'methods' => 'POST,
'callback' => 'your_function_callback',
'permission_callback' => function() {
if ( !is_user_logged_in() ) {
return new WP_Error('rest_not_logged_in', 'You must be logged in.', ['status' => 401]); // Use WP_Error
}
return true;
}
]);
The cause of this is actually because Wordpress requires you to include a nonce with each request when making ajax requests to its api route. Read more on their official documentation.
Taken directly from their doc: 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. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.
To solve this, you just need to include a nonce in your ajax call either through the POST data or in the header. You can create a wordpress nonce like so
wp_create_nonce('wp_rest')
Note that you must use wp_rest
as the action for this nonce.
Add the nonce into your javascript file through PHP by using wp_localize_script
wp_localize_script('your-script-name', 'wp_data', array(
'nonce' => wp_create_nonce('wp_rest'),
));
Then in your script simply include it in your ajax call in the POST data or in the header, with the parameter as _wpnonce
Example:
var formData = new FormData(form);
formData.append("_wpnonce", wp_data.nonce);
jQuery.ajax({
url: ...,
type: "POST",
data: formData,
success: function(response) {
...
},
error: function(response) {
...
}
});
Hope that was helpful! Let me know if you have any questions.
Comments
test
♡
❤️
test