rest_authentication_errors
概述
rest_authentication_errors 是一个 WordPress REST API 的过滤器钩子,用于处理认证过程中的错误传递。它允许认证方法返回 WP_Error、null 或 true 来指示认证状态,并支持多个认证方法的协同工作。
关键要点
- 该钩子用于从认证方法向 API 传递 WP_Error 实例,以处理认证错误。
- 认证方法应检查是否被使用,若未使用则返回 null,以便其他方法尝试;若成功则返回 true。
- 返回的 WP_Error 应匹配 API 内部使用的格式,特别是状态数据。
- 钩子参数 $errors 可以是 WP_Error(认证错误)、null(未使用认证方法)或 true(认证成功)。
- 在 WordPress 4.4.0 版本中引入,常用于 WP_REST_Server::check_authentication() 方法。
代码示例
public function wpdocs_sanitize_nonce( $errors ) {
// 如果 rest_route 未定义,则直接返回(通常不会发生)
if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
return $errors;
}
$route = ltrim( $GLOBALS['wp']->query_vars['rest_route'], '/' );
// 确保只处理特定的 REST 请求
if ( strpos( $route, 'shopwp/v1' ) !== 0 ) {
return $errors;
}
if ( ! empty( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
if ( ! wp_verify_nonce($nonce, 'wp_rest') ) {
// Nonce 验证失败,创建一个新的
$_SERVER['HTTP_X_WP_NONCE'] = wp_create_nonce( 'wp_rest' );
}
}
return $errors;
}注意事项
- 在实现回调时,应先检查 $errors 是否为 null,以避免覆盖其他认证方法的错误。
- 该钩子常用于解决缓存插件导致的 nonce 过期问题,如示例中所示。
- 确保只针对特定的 REST 路由进行处理,以避免影响其他 API 端点。
Filters REST API authentication errors.
Description
This is used to pass a WP_Error from an authentication method back to the API.
Authentication methods should check first if they’re being used, as multiple authentication methods can be enabled on a site (cookies, HTTP basic auth, OAuth). If the authentication method hooked in is not actually being attempted, null should be returned to indicate another authentication method should check instead. Similarly, callbacks should ensure the value is null before checking for errors.
A WP_Error instance can be returned if an error occurs, and this should match the format used by API methods internally (that is, the status data should be used). A callback can return true to indicate that the authentication method was used, and it succeeded.
Parameters
Source
return apply_filters( 'rest_authentication_errors', null );
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |
Skip to note 2 content
andrewmrobbins
I needed to use this hook to fix a nonce expiration bug.
My plugin uses the WP REST API to fetch data on the front-end. A longstanding issue has been that other caching plugins could sometimes cache this nonce, throwing a 403 error for my users.
I used this solution:
public function wpdocs_sanitize_nonce( $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 request only if ( strpos( $route, 'shopwp/v1' ) !== 0 ) { 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; }