有几个选项用于API验证。基本的选择归结为:
- 你是在网站上运行的插件/主题?使用cookie认证
- 你是一个桌面/网络/移动客户端访问外部网站?使用 OAuth身份验证,应用程序密码或基本身份验证
Cookie认证
创建nonce
<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
使用它
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
JQuery例子:
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
注:使用easyUI的form表单提交就悲剧了,它好像不能设置请求header(如果可以,请指教)
OAuth认证
OAuth插件:
https://github.com/WP-API/OAuth1
如何使用OAuth身份验证的示例:
https://github.com/WP-API/example-client