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.

 

https://gist.github.com/8e0d7235bd462bcb65c55223aa861f8f

like so

screenshot-2016-11-04-12-39-05

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.

https://gist.github.com/0c873a0560f68b94452f86c643ccf90b

 

Help other people find this

2 Responses to “WordPress REST API: Forcing authentication for all requests”

  1. Happy Guy says:

    Old post I know but it really helped me out. I received an error when modifying the plugin source. I won’t go into that but I found that I did not have to make the change anyway. Adding the hook in my plugin sufficiently locked it down.

Leave a Reply

Your email address will not be published. Required fields are marked *