Environment: WordPress 4.7 or more, WP comes with the REST API v2
Goal: Use JavaScript to interact with the WP Rest API, where edits, additions, deletions, and so on require OAuth authentication authorization
Method:
Step One: Install WP plugin jwt-authentication-for-wp-rest-api
Step Two: according to the JWT plugin documentation , modify the. htaccess
General server (. Access file configuration):
Rewriteengine Onrewritecond%{http:authorization} ^ (. *) Rewriterule ^ (. *)-[e=http_authorization:%1]setenvif Authorization "(. *)" http_authorization=$1
Step Three: Modify the wp-config.php according to the JWT plugin documentation
Define (' Jwt_auth_secret_key ', ' Your-top-secrect-key ');d efine (' jwt_auth_cors_enable ', true);
The ' Your-top-secrect-key ' can refer to the parameter values in the https://api.wordpress.org/secret-key/1.1/salt/, such as:
Define (' Jwt_auth_secret_key ', ' =i ' g+h|} FSLR F,$8~&n#pamfpzrk6,e]dg.-<|jip (h8c%) ^UO/L~$3},FC ');
Step four: request token in JS, and then attach the token value in the header when editing and so on
$.ajax ({url: "Http://localhost/wp-json/jwt-auth/v1/token", Method: "POST", data:{Username: "Admin", Password: "1234 "}, Success:function (res) {Console.log (res); Token = Res.token; $.ajax ({url: "Http://localhost/wp-json/wp/v2/posts/1", Method: "POST", Beforesend:function (XHR) {XH R.setrequestheader ("Authorization", "Bearer" + Token); }, data:{"title": "Hello API"}, Success:function (res) {Console.log (res); }, Error:function (res) {Console.log (res); } }); }, Error:function (res) {Console.log (res); }});
WP Rest API authorization Method Step (using JWT authentication plugin)