Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WordPress: How to make private access to REST API with JWT Auth plugin

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;

} );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading