So before I went down the JWT route, whilst it would work, I haven't finished it yet and doing so would require lots of testing. Even more so, I went down the JWT route because I couldn't get WP authentication to work before. :/
But now I have.
Currently the UX for the voting plugin is not ideal. There should be one dashboard where the awards are managed, not 4+. However, to control permissions we separated them into different dashboards where WordPress menu hook allows such control.
We need to know whether a user is authorized to do such a task, mutate or access a resource.
This is how!
- Define the permission level in the permission_callback:
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/hi', array(
'methods' => 'GET',
'callback' => function() {
return 'Hello world!';
},
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
));
});
-
Ensure a) Cookie credentials are included in the API response b) The Nonce is also included in the API response
Double token auth!
fetch('/wp-json/myplugin/v1/author/hi', {
credentials: 'include',
headers: {
'content-type': 'application/json',
'X-WP-Nonce': wpApiSettings.nonce
}
})
.then(response => response.json())
.then(console.log)
.catch(console.warn)