Last active
September 5, 2024 01:55
-
-
Save danielbachhuber/8f92af4c6a8db784771c to your computer and use it in GitHub Desktop.
Disable WP REST API requests for logged out users
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); |
still access /wp/v2/posts without passing an Authorization header.
@quasivivo how can we do that ? thx
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?
Hi, any idea to perform the same require authentification for 1 or more custom posts types only ? Not for all REST API request.
thx
@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
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; });