我的wordpress站点位于Akamai后面,这是一个类似Cloudflare的缓存服务。
我执行以下API调用:
GET /wp-json/mytheme/v1/get-posts?post_type=videos这是使用apiFetch从‘@wordpress/api-fetch’完成的;
它会自动将其包含在请求头中。
X-WP-Nonce: 12323423这样可以工作到24小时后,当现在的过期。缓存仍然继续使用过期的当前,从而导致403禁止页和一个破页。
如果我发出相同的请求,没有任何标题,它的工作非常好。
Wordpress中是否有一种方法可以禁用或删除仅用于GET请求的Nonce?
甚至通过拦截请求来删除X-WP-Nonce头文件?
这是我从wordpress前端发出请求的代码。
apiFetch({
path: '/wp-json/mytheme/v1/get-posts?post_type=videos',
parse: false,
});发布于 2019-06-27 22:52:55
基于身份验证文档,这里 --需要在每个请求中传递一个当前密钥。
因此,如果在前端缓存的nonce密钥超过了其生存期,则需要在身份验证步骤之前连接到API请求,并将缓存的nonce密钥替换为有效的密钥。
WordPress为我们提供了一个rest_send_nocache_headers过滤器来连接(看这里)。这允许我们在身份验证之前执行一个操作。
$send_no_cache_headers = apply_filters('rest_send_nocache_headers', is_user_logged_in());
if (!$send_no_cache_headers && !is_admin() && $_SERVER['REQUEST_METHOD'] == 'GET') {
$nonce = wp_create_nonce('wp_rest');
$_SERVER['HTTP_X_WP_NONCE'] = $nonce;
}在上面的示例中,我们将is_user_logged_in()函数作为参数连接到过滤器中。这将返回真假。
然后在我们的查询中,如果用户没有登录,他们就不在管理员中,这是一个GET请求,我们继续用一个有效的键切换无效的当前键。
发布于 2020-12-01 19:16:51
为了添加被接受的答案,我找到了一个类似的解决方案,但是在rest_authentication_errors运行之前,我找到了一个链接到rest_cookie_check_errors的解决方案。
由于底层问题是立即过期的,所以当用户登录时(即没有发送缓存头时)以及注销时,您可能会遇到这个问题。我还进行了一些检查,以确保我们只处理REST请求--我检查了'rest_route‘查询变量,但可能有更好的方法。
add_filter( 'rest_authentication_errors', function( $errors ) {
// Bail if rest_route isn't defined (shouldn't happen!)
if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
return $errors;
}
$route = ltrim( $GLOBALS['wp']->query_vars['rest_route'], '/' );
// Ensure we're dealing with our REST requst.
if ( 0 !== strpos( $route, 'my-awesome-namespace/v1' ) ) {
return $errors;
}
if ( ! empty( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
// Nonce check failed, so create a new one.
$_SERVER['HTTP_X_WP_NONCE'] = wp_create_nonce( 'wp_rest' );
}
}
return $errors;
}, 10 );https://wordpress.stackexchange.com/questions/341496
复制相似问题