WordPress REST API: Forcing authentication for all requests
I’m working on a project that will be using WordPress’s REST API to feed JSON data to a mobile app. We only want authenticated users to be able to query the REST API.
Out of the box, the REST API exposes all public content by GET request without any authentication requirements.
We’re using Enrique Chavez‘s JWT Authentication for WP REST API to allow us to authenticate users and get an authentication token. We have made a modification to the JWT auth plugin to expose the “validate_token” method by adding the following code to line 143 of the class-jwt-auth.php file.
This gives us access to the validate_token method elsewhere in WordPress.
We then hook into the REST API’s “rest_pre_dispatch” hook to require the presence of a valid token before exposing any API data with this custom filter in our theme’s functions.php file.