• HI I have setup a number of REST endpoints and an oauth1 server that all works fine, but I was playing around with JWT plugin and found that a function I use to disallow REST access in the absence of login prevents this plugin from working. If I disable it, I can sucessfully get a token, but that would mean my REST endpoints are open to anyone, and I don’t want that. Here is the code I am using to block non logged in users:

    /*
     * Only allow Admin users to view WP REST API JSON Endpoints
     */
    function mytheme_only_allow_logged_in_rest_access( $access ) {
    
    	if( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
    		return new WP_Error( 'rest_cannot_access', __( 'Only authenticated users can access the REST API.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
    	}
    	return $access;
    }
    add_filter( 'rest_authentication_errors', 'mytheme_only_allow_logged_in_rest_access' ); 

    And like I said, this works fine with the oauth server, but not with your JWT plugin. Any ideas how to keep my restrictions and still supply JWT tokens and access? Thanks!

Viewing 1 replies (of 1 total)
  • Thread Starter Stephen S

    (@ssuess)

    Well, I figured out a workaround which should be good for my purposes. I changed my function to look like this:

    function mytheme_only_allow_logged_in_rest_access( $access ) {
    if (!strpos($_SERVER['REQUEST_URI'], "jwt-auth/v1/token")) {
    	if( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
    		return new WP_Error( 'rest_cannot_access', __( 'Only authenticated users can access the REST API.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
    	} }
    	return $access;
    }
    add_filter( 'rest_authentication_errors', 'mytheme_only_allow_logged_in_rest_access' );

    Hope this helps someone else…

    • This reply was modified 7 years, 1 month ago by Stephen S.
Viewing 1 replies (of 1 total)
  • The topic ‘Not working when login required’ is closed to new replies.