wp rest api 授权方法步骤(使用JWT Authentication插件)

环境:wordpress 4.7 以上,WP自带的 rest api v2 

目标:使用javascript与wp rest api交互,其中编辑、新增、删除等需要Oauth认证授权

方法:

  步骤一: 安装wp插件 jwt-authentication-for-wp-rest-api

 

  步骤二: 根据jwt插件文档,修改.htaccess 

  一般服务器:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

  wpengine:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

  

  步骤三: 根据jwt插件文档,修改wp-config.php

define('JWT_AUTH_SECRET_KEY', 'your-top-secrect-key');
define('JWT_AUTH_CORS_ENABLE', true);

  其中的 'your-top-secrect-key' 可以参考https://api.wordpress.org/secret-key/1.1/salt/中的参数值,如:

define('JWT_AUTH_SECRET_KEY', '=i``G+H|} fSLR f,$8~&N#paMfPzrk6,e]Dg.-<|jip(H8C%) ^uO/ l~$3},fC');

  

  步骤四:在js中请求token,然后在编辑等操作时在header中附带上token值

$.ajax({
  url:"http://localhost/wp-json/jwt-auth/v1/token",
  method:"POST",
  data:{
    username:"admin",
    password:"123456"
  },
  success:function(res){
    console.log(res);
    Token = res.token;
    $.ajax({
      url:"http://localhost/wp-json/wp/v2/posts/1",
      method:"POST",
      beforeSend: function(xhr) {
        xhr.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);
  }
});

  

ps:欢迎访问我的小站:模板世界,获取更多有用的前端资源。

posted @ 2017-07-11 11:03  xh_a1216  阅读(3036)  评论(0编辑  收藏  举报