WP Rest API authorization Method Step (using JWT authentication plugin)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.