wp rest api 授权要领法式(使用JWT Authentication插件)

时间:2022-05-15 08:03:06

  法式一: 安置wp插件 jwt-authentication-for-wp-rest-api

  法式二: 按照jwt插件文档,,改削.htaccess 

  一般处事器(.access文件配置):

RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1] 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);   } });