Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Last active September 11, 2023 21:52
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save danielbachhuber/8f92af4c6a8db784771c to your computer and use it in GitHub Desktop.
Save danielbachhuber/8f92af4c6a8db784771c to your computer and use it in GitHub Desktop.
Disable WP REST API requests for logged out users
<?php
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error( 'restx_logged_out', 'Sorry, you must be logged in to make a request.', array( 'status' => 401 ) );
}
return $result;
});
Copy link

ghost commented Jan 6, 2017

There's a plugin that does this now. https://wordpress.org/plugins/disable-json-api/

@quasivivo
Copy link

With lines 4-6 included, I noticed that I could still access /wp/v2/posts without passing an Authorization header. Removing those lines seemed to require auth for all requests, which is what I was after.

add_filter( 'rest_authentication_errors', function( $result ) { if ( ! is_user_logged_in() ) { return new WP_Error( 'restx_logged_out', 'Sorry, you must be logged in to make a request.', array( 'status' => 401 ) ); } return $result; });

@chambord7
Copy link

chambord7 commented Jan 24, 2017

still access /wp/v2/posts without passing an Authorization header.

@quasivivo how can we do that ? thx

@chambord7
Copy link

https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests
According to the official FAQ, it's a "good practice" to add lines 4-6; what I am missing here to protect the data?

@Nayir
Copy link

Nayir commented Apr 5, 2017

Hi, any idea to perform the same require authentification for 1 or more custom posts types only ? Not for all REST API request.
thx

@mriqbalhussain
Copy link

mriqbalhussain commented Sep 11, 2023

@Nayir you can add the show_in_rest argument by user permission like

`
$show_in_rest = current_user_can( 'edit_others_posts' );

register_post_type('mycpt', array(
'show_in_rest' => $show_in_rest
));

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment