Securing REST API in Wordpress

ARTRU

Is it possible to disable REST API?

This is the same question that I have been thinking about for a long time. After I learned about the API, I got the answer.

REST API is fully integrated in WordPress version 4.7 (2016). So the WordPress Admin functions are dependent on the API.

However, you can use filters to authenticate API user requests. This effectively prevents external API access without affecting the ADMIN account.

Insert php code to disable REST API

Insert the code into the functionc.php file of the theme / child theme or mu-plugins (I use mu-plugins as the functions configuration file for the website).

PHP code:

/** Tắt REST API cho người dùng chưa đăng nhập */
add_filter( 'rest_authentication_errors', function( $result ) {
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            __( 'You are not currently logged in.' ),
            array( 'status' => 401 )
        );
    }
    return $result;
});
COMMENT

Related Articles