我正在开发一个前端应用程序,它与位于单独域上的 wordpress API 相关联。
我想要检索帖子草稿,以便当用户在 wordpress 管理面板中单击“预览帖子”时,它会打开我的应用程序并显示正确的内容。
我正在将一些 Javascript 加载到 WP 管理中,这样我就可以使用 wp_nonce token 修改管理面板中的所有“预览帖子”链接以进行身份验证。这是使用以下代码片段完成的,该代码片段将预览帖子链接调整为例如:http://example.com/blog?p=127&preview=true&auth=16045802ee
function admin_inline_js(){
// Grab URL
echo '
<script>
document.addEventListener("DOMContentLoaded", function() {
// Grab all preview anchors
var anchors = document.querySelectorAll("a[href*=\'preview=true\']"), i;
// Loop through and amend to remove the trailing slash, as WP doesnt provide any easy method to achieve this.
for(i = 0; i < anchors.length; i++) {
anchors[i].href = anchors[i].href.replace("blog/", "blog") + \'&auth=' . wp_create_nonce('wp_rest') .'\';
}
});
</script>
';
}
add_action( 'admin_print_scripts', 'admin_inline_js' );
在 http://example.com/blog?p=127&preview=true&auth=16045802ee
处,auth
参数然后用于将请求发回 wordpress 以检索 ID 为 127 的草稿,随机数标记为 16045802ee
。然而,这不起作用,我收到了这样的回复:
object(stdClass)#459 (3) { ["code"]=> string(25) "rest_cookie_invalid_nonce" ["message"]=> string(23) "Cookie nonce is invalid" ["data"]=> object(stdClass)#532 (1) { ["status"]=> int(403) } }
任何人都可以发现我在这里做错了什么吗? :/
谢谢。
最佳答案
您面临两个问题:
Wordpress“nonce”是一种仅用于防止 CSRF token 的工具。在为管理面板编写插件时非常有用,但对于针对 API 进行身份验证没有用。
默认规定的 .htaccess 文件会阻止通过 API 传递身份验证详细信息。
您需要通过 API 传递身份验证详细信息,以便接收包含 protected 数据的响应。为简单起见,我建议首先使用 HTTP Basic Auth 使其正常工作,并可选择在将来使用更安全的身份验证方法(例如 OAuth)来增强您的代码。
我建议专门为 API 使用创建一个新用户,而不是在服务器上的文本文件中传递管理员详细信息。
创建用户后,您可以使用 PHP 中的简单 cURL 请求草稿帖子,如下所示:
$apiUsername = "apiuser";
$apiPassword = "sup3r-s3cr3t-p455w0rd";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/wp-json/wp/v2/posts/127");
curl_setopt($ch, CURLOPT_USERPWD, "$apiUsername:$apiPassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
$postObject = json_decode($json);
这将设置包含用户名和密码的请求 header ,只要在到达 Wordpress 之前没有任何东西干扰此 header ,您将在 $postObject
中收到您的帖子详细信息,您可以停止阅读这里。大功告成。
但是,为了获得额外的乐趣,Wordpress 规定的默认 .htaccess
文件会删除 HTTP header ,因此如果您正在使用它,则需要自己修复它。基本上,Wordpress 脚本需要在 $_SERVER
变量中看到 PHP_AUTH_USER
和 PHP_AUTH_PW
键才能工作。
快速修复是将以下规则作为第一个 RewriteRule 包含在 .htaccess 中:
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
这会将 header 拆分为前缀为“REMOTE_USER”的变量,并且可以使用以下 PHP 再次填充预期的字段(也许这可以放在 index.php
中)。
$userPass = $_SERVER["REDIRECT_REMOTE_USER"];
if(!empty($userPass)
&& strstr($userPass, "Basic")) {
$userPass = substr($userPass, strpos($userPass, " ") + 1);
$userPass = base64_decode($userPass);
$userPass = explode(":", $userPass);
$_SERVER['PHP_AUTH_USER'] = $userPass[0];
$_SERVER['PHP_AUTH_PW'] = $userPass[1];
}
关于php - WP-API 检索草稿 "Cookie nonce is invalid",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46222009/