• TMS

    (@themysticalsock)


    This access policy: https://aamplugin.com/policy/hide-and-restrict-access-to-all-posts, required the plus package. I didn’t really want to get that simply becuase I wanted to restrict access to all posts, when everything else is already restricted.

    Rather than have to go one by one through all posts (or let users deal with the Access Manager), I found a nice piece of code that I changed a bit for AAM.
    (source: https://stackoverflow.com

    Basically it allows one to restrict all posts (and everything else) but let JWT auth (API v2) through:

    1) create a new php file in mu-plugins something like “restrict-api.php”
    2) add this code

    <?php add_filter( 'rest_authentication_errors', function( $result ) {
        // If a previous authentication check was applied,
        // pass that result along without modification.
        if ( true === $result || is_wp_error( $result ) ) {
            return $result;
        }
    global $wp;
        // No authentication has been performed yet.
    // Return an error if user is not logged in and not trying to login.
    //Change the Not Authorised message if you wish, but keep the single quotes 'like this'
    if ( ! is_user_logged_in() && $wp->request !== 'wp-json/aam/v2/authenticate' && $wp->request !== 'wp-json/aam/v2/jwt/revoke' && $wp->request !== 'wp-json/aam/v2/jwt/refresh' && $wp->request !== 'wp-json/aam/v2/jwt/validate' ) {
        return new WP_Error(
            'rest_no_auth',
            __( 'Not Authorised' ),
            array( 'status' => 401 )
        );
    }
        // Our custom authentication check should have no effect
        // on logged-in requests
        return $result;
    });

    3) save it
    …and you’re done!

    If you want to allow another API route through, just add it to the list above in this format:
    && $wp->request !== 'wp-json/wp/v2/posts'

    This is only recommended if you want to block all API routes except for authenticated users. Clear your caches if you see any issues with access after you’ve saved the php file.

    Hope this helps someone, somewhere…

    I’m not responsible if you mess up your wp install – but you just easily delete the php file if you do get into any trouble, I won’t reply to this so don’t ask for support.

    • This topic was modified 3 years, 10 months ago by TMS.
  • The topic ‘Hide and Restrict access to all posts’ is closed to new replies.