Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
});
@andrewhl

This comment has been minimized.

Copy link

@andrewhl andrewhl commented Nov 22, 2016

Where does this go?

@hwbirds

This comment has been minimized.

Copy link

@hwbirds hwbirds commented Nov 23, 2016

Took effect for me when adding to top of plugin.php in the 'rest-api' plugin directory.

@Steve62

This comment has been minimized.

Copy link

@Steve62 Steve62 commented Dec 6, 2016

Put it in functions.php in your theme directory.

@ramseyp

This comment has been minimized.

Copy link

@ramseyp ramseyp commented Jan 6, 2017

Is this a simple plugin on the repo yet? Seems it could be. Or should be. Not part of a larger plugin, mind you. Just merely requiring authentication for api access.

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jan 6, 2017

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

@quasivivo

This comment has been minimized.

Copy link

@quasivivo quasivivo commented Jan 11, 2017

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

This comment has been minimized.

Copy link

@chambord7 chambord7 commented Jan 24, 2017

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

@quasivivo how can we do that ? thx

@chambord7

This comment has been minimized.

Copy link

@chambord7 chambord7 commented Jan 24, 2017

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

This comment has been minimized.

Copy link

@Nayir 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

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