WordPress RESTful API 的授权方式

WordPress 5.6 以后内置了RESTful API,并且建议用户一定不要关闭,否则会影响WordPress后台的某些功能。调用某些接口的时候,会提示

{code: "rest_cannot_edit", message: "抱歉,您不能编辑此用户。", data: {status: 401}}

Cookie Authentication 是 WordPress 内置的身份验证方法。登录仪表板时,会生成cookie。 但是,REST API包含一种称为nonce的技术来避免CSRF的问题。

使用内置Javascript API的开发人员,WordPress 会自动处理 nonce。自定义数据模型可以扩展wp.api.models.Base 确保为任何自定义请求正确发送。

对于自己启用 Ajax的情况,需要在请求的地址后面,加上一个 nonce 参数“_wpnonce”。可以使用 wp_create_nonce(‘wp_rest’) 生成 _wpnonce。举个例子:

http://www.vtheme.cn/wp-json/wp/v2/users/2?_wpnonce=9aaea876fd

axios 例子:

var wpnonce = document.querySelector("input[name='wp_create_nonce']").value;
var url = document.querySelector(".ajax-form").getAttribute("action") + "?_wpnonce=" + wpnonce;
var userId = document.querySelector("input[name='id']").value;
var formData = new FormData();
formData.append('id', userId);
formData.append('nickname', '木瓜');

axios({
    headers: { 'Content-Type': 'multipart/form-data' },
    method: 'post',
    url: url,
    responseType: 'json',
    data: formData,
})
    .then(function (response) {
        console.log("response: ", response);
    })
    .catch(function (error) {
        console.log("error:", JSON.stringify(error) );
    });

除了这个,还有两种方式 处理接口权限的问题,推荐使用类似第三种 JSON Web Token.


Application Passwords

WordPress 5.6 以前是个插件,现在已经集成到WordPress中了。

functions.php 中添加 add_filter( ‘wp_is_application_passwords_available’, ‘__return_true’ ); 进行开启。然后在控制面板->所有用户->编辑用户中,即出现应用程序密码设置。或者使用基于 Cookie Authentication 的方法创建,相关接口参看:https://wordpress.org/plugins/application-passwords/

应用程序密码允许通过非交互式系统(例如XML-RPC或REST API)进行身份验证,而无需提供您的实际密码。应用密码很容易被撤销。它们不能用于通过传统方式登录您的网站。

 


JSON Web Tokens

插件地址: http://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

VScode RESTclinet 例子:

###
POST http://www.vtheme.cn/wp-json/jwt-auth/v1/token
content-type: application/json

{
    "username": "test",
    "password": "123123"
}

###
GET http://www.vtheme.cn/wp-json/wp/v2/users/me/application-passwords
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1LKJ9.eyJpc3MiOiJodHRwOlwvXC93d3cudmVyeXRoZW1lLmGJKSIsImlhdCI6MTYyNTg1NTU4NSwibmJmIjoxNjI1ODU1NTg1LCJleHAiOjE2MjY0NjAzODUsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.vgfz24DIDFddML3m4OplbJgvWcmCsktSdf14_Jhjkhjk

 

参考:http://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

收藏 0
评论
WordPress 主题开发
WordPress 自定义文章排序
2021-07-04 17:43:11
WordPress 主题开发
WordPress 调用自定义头像
2021-07-25 13:17:54
生成中...
登录
注册
重置密码