
Trying to access your custom posttype through the WordPress rest-API, but want to make sure the session has the correct permissions? Well, according to the docs you could do this with Basic Authentication.
However it did not seem to work. I was trying the proof of concept with a request like this:
$url_test = 'https://yourtestwebsite.url/wp-json/wp/v2/yourcustomposttype';
$user = 'yourapiusername';
$pass = 'yourapiuserpassword';
$auth = base64_encode($user.':'.$pass);
$ctx = stream_context_create(array('http' => array('header' => 'Authorization: Basic '.$auth)));
$data = file_get_contents($url_test, false, $ctx);
Adding yourcustomposttype to the rest api is simple, but you can not add any permissions check. So I added an extra check for the correct permission first before adding the custom endpoint, like so:
add_action('init', function () {
if (is_access_to_restapi_allowed() == true) {
global $wp_post_types;
if (isset($wp_post_types['yourcustomposttype'])) {
$wp_post_types['yourcustomposttype']->show_in_rest = true;
$wp_post_types['yourcustomposttype']->rest_base = 'yourcustomposttype';
$wp_post_types['yourcustomposttype']->rest_controller_class = 'WP_REST_Posts_Controller';
// add the meta data!
register_rest_field('yourcustomposttype', 'meta', array(
'get_callback' => function ($data) {
return get_post_meta($data['id'], '', '');
}, ));
}
}
});
I checked first with the following check, but that did not work:
function is_access_to_restapi_allowed() {
return current_user_can('whateverpermissionyourequireforaccess');
}
WordPress will not log you in based on the Basic Authentication header.
So I had to change that function and check the header first, and login with the submitted details. Then I could check if that user has the correct permissions, like so:
function is_access_to_restapi_allowed() {
$headers = apache_request_headers();
if ((!empty($headers)) && (is_array($headers))) {
if ((key_exists('Authorization', $headers)) && !empty($headers['Authorization'])) {
$auth_header = $headers['Authorization'];
list($username, $password) = explode( ':', base64_decode( substr( $auth_header, 6 ) ) );
$user = wp_authenticate( $username, $password );
if ($user->has_cap('whateverpermissionyourequireforaccess') == true) {
return true;
}
}
}
return false;
}
That’s al folks!
Have a nice day…