Paulund

Only Allow Access To REST To Logged In Users

The WordPress REST API is a very exciting feature of WordPress, it was introduced into the core in version 4.7 and is getting a lot of attention from the developers to move this feature forward. If you would like to learn more about the REST API you should read the following article WordPress Rest API.

One thing I don't like about the REST API is that some endpoints can be accessed and return data even from unauthorised sources. Although this isn't a security risk as most of the endpoints that exist are for content that are open to public access anyway, I still don't like the fact that anybody can make a call to /wp-json/wp/v2/posts and get a JSON with all the posts and the content. You can authenticate the WordPress REST request with either cookie authentication, basic authentication or OAuth authentication.

But even when the requests are authenticated you can still get access to endpoints such as posts without the need to be authenticated. Therefore I wanted to find out how we can block access to all endpoints on the API unless the user is logged in. Inside the file /wp-includes/rest-api/class-wp-rest-server.php there's a function called check_authentication which returns a filter of rest_authentication_errors, we can use this filter to make sure only logged into users can have access to the REST API.

When a request is made with the correct authorised credentials they will be given a user account on WordPress.

add_filter( 'rest_authentication_errors', 'only_authorised_rest_access');

function only_authorised_rest_access( $result )
{
    if( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_unauthorised', __( 'Only authenticated users can access the REST API.', 'rest_unauthorised' ), array( 'status' => rest_authorization_required_code() ) );
    }

    return $result;
}