I’m looking for a way to disable Rest API for a user role called ‘external_user’ (disable wp-json queries.)

This user role can see right now alot of posts and pages information with when we put wp-json on the URL (users, pages, posts…)

I use actually the plugin DISABLE REST API but it prevent only not logged users to see json informations. i need to do the same thing with external_user role.

If it’s not possible, can I redirect this user role (and only external_user role) to 404 pages if he try to put an URL with wp-json ?

Thanks.

2 Answers
2

The plugin has a filter drh_allow_rest_api which determines whether the current user has full access and can skip the whitelist check. By default this is just is_user_logged_in():

/**
 * Allow carte blanche access for logged-in users (or allow override via filter)
 *
 * @return bool
 */
private function allow_rest_api() {
    return (bool) apply_filters( 'dra_allow_rest_api', is_user_logged_in() );
}

so we can hook that to clear the ‘is_user_logged_in’ flag if it’s an external_user:

function dra_disallow_external_users( $logged_in ) {
    if ( $logged_in ) {
        $user = wp_get_current_user();
        if ( $user && in_array( 'external_user', $user->roles ) ) {
            // Treat external_users as unauthenticated
            // i.e. only allow access to whitelisted endpoints.
            return false;
        }
    }

    return $logged_in;
}
add_filter( 'dra_allow_rest_api', 'dra_disallow_external_users', 10, 1 );

Leave a Reply

Your email address will not be published. Required fields are marked *