Home > Back-end >  WordPress: How to make private access to REST API with JWT Auth plugin
WordPress: How to make private access to REST API with JWT Auth plugin

Time:10-18

I downloaded, installed and activated the plugin "JWT Authentication for the WP REST API".

And I see how I can obtain JWT access token when sending credentials from the client.

But I don't see how to use the plugin with the existing WordPress REST API.

For example, if I follow by the link like /wp-json/wp/v2/posts or /wp-json/wp/v2/posts/1, I still fetch the resource without any restricting the access, so the access is still public.

So how to restrict the access making it private with the plugin?

CodePudding user response:

You can use the rest_authentication_errors hook filter to restrict the REST access coupled with is_user_logged_in() and user_can().

<?php

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

    if ( true === $result || is_wp_error( $result ) ) {

        return $result;

    }

    if ( ! is_user_logged_in() && ! user_can( get_current_user_id(), 'export' ) ) {
        
        return new WP_Error(
            'rest_not_logged_in',
            __( 'Silence is golden.' ),
            array( 'status' => 401 )
        );

    }

    return $result;

} );
  • Related