admin管理员组

文章数量:1336645

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.

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.

Share Improve this question edited May 19, 2020 at 0:30 Samuel asked May 13, 2020 at 7:05 SamuelSamuel 3541 gold badge11 silver badges32 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3 +50

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 );

If you wan to accomplish it without plugin you can follow this approach. This will check two things.

  • If user logged in or not.
  • If logged in user is 'external_user' or not.

.

add_filter( 'rest_authentication_errors', 'wp_snippet_disable_rest_api' );
function wp_snippet_disable_rest_api( $access ) {
    if(!is_user_logged_in() || (is_user_logged_in() && current_user_can('external_user'))){
        return new WP_Error( 'rest_disabled', __('The WordPress REST API has been disabled.'), array( 'status' => rest_authorization_required_code()));
    }
}

本文标签: postsDisable REST API for a user ROLE