Force REST API Authentication for each request method

You can’t really apply authentication based directly on whether the request is GET or otherwise, but can forcefully apply authentication requirements globally in that manner, if you like.

I’ve been quite verbose with the code to illustrate what’s happening:

add_filter( 'rest_authentication_errors', function ( $error ) {

    /**
     * If it's a WP_Error, leave it as is. Authentication failed anyway
     *
     * If it's true, then authentication has already succeeded. Leave it as-is.
     */
    if ( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) === 'get' && !is_wp_error( $error ) && $error !== true ) {

        if ( !is_user_logged_in() ) {
            $error = new \WP_Error( 'User not logged-in' );
        }
        
    }

    return $error;
}, 11 );

Assumptions:

  • PHP is at least version 5.3
  • We’re only testing GET requests
  • If an authentication error has been met before this filter is executed, then we leave the error as-is.
  • If there is no error, and in-fact it’s set to true, then this means authentication has already succeeded and there’s not need to block anything.
  • We’re only testing whether or not the user making the request is logged-in i.e. is authenticated with WordPress.