Can not set OAuth on wordpress REST api

2019-06-12 06:02发布

问题:

I want to implement Rest api with authorization in my Wordpress website. the version of Wordpress is 4.9.5 and REST api version 2.0-beta15. For securing my apis i need to implement OAuth on my site and at first, I implement WordPress REST API – OAuth 1.0a Server from this link and this useful link. But had these issues with plugin:

  • Rest-calls still works without authorization and every un-authorized user can call my rest-apis.
  • I want to implement this inside my Android app so I had to handle all steps in the background, but with this plugin, I should show many webView to user and user should fill them and the final token is also shown to the user in webview and this does not sound good for me.

So I looking for another plugin and find JWT Authentication for WP-API. This plugin is easier and handy. I followed the instructions and can get token and add to request header to make a request and if it is the valid response is 200 and if not need to validate. Every thing seems to work fine!

But the same problem:

  • every single REST API is even working without authorization header and if I do not put header the result is 200 And all request works as before without any Authorization

This is despite documents that say:

Once you get the token, you must store it somewhere in your application, ex. in a cookie or using localstorage.

From this point, you should pass this token to every API call

So now I see that I cloud not restrict API call to have Authorization header in both plugins, how I can achieve that and what is the best solution?

回答1:

I finally solve this problem with this plugin:

Disable REST API and Require JWT / OAuth Authentication

As its name says it will do exactly what i want. It works on both plugin i used

  • JWT Authentication for WP REST API
  • WP OAuth Server

And restricts all api calls that not authorized and works fine. So i my best practice is JWT for Oauth + Disable REST API and Require JWT / OAuth Authentication and they are very good combination to implement OAuth in android application for word-press.