rest_cookie_check_errors

函数
rest_cookie_check_errors ( $result )
参数
  • (WP_Error|mixed) $result Error from another authentication handler, null if we should handle it, or another value if not.
    Required:
返回值
  • (WP_Error|mixed|bool) WP_Error if the cookie is invalid, the $result, otherwise true.
定义位置
相关方法
rest_cookie_collect_statusget_core_checksumsrest_application_password_check_errorsis_client_errorms_cookie_constants
引入
4.4.0
弃用
-

rest_cookie_check_errors: 这个过滤器钩子允许开发者修改在检查cookie的有效性时返回的错误。

当使用基于cookie的认证时,检查是否有错误。

WordPress内置的cookie认证对于登录的用户来说始终是有效的。然而,API必须为每个请求检查nonces,以确保用户不会受到CSRF的攻击。

function rest_cookie_check_errors( $result ) {
	if ( ! empty( $result ) ) {
		return $result;
	}

	global $wp_rest_auth_cookie;

	/*
	 * Is cookie authentication being used? (If we get an auth
	 * error, but we're still logged in, another authentication
	 * must have been used).
	 */
	if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
		return $result;
	}

	// Determine if there is a nonce.
	$nonce = null;

	if ( isset( $_REQUEST['_wpnonce'] ) ) {
		$nonce = $_REQUEST['_wpnonce'];
	} elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
		$nonce = $_SERVER['HTTP_X_WP_NONCE'];
	}

	if ( null === $nonce ) {
		// No nonce at all, so act as if it's an unauthenticated request.
		wp_set_current_user( 0 );
		return true;
	}

	// Check the nonce.
	$result = wp_verify_nonce( $nonce, 'wp_rest' );

	if ( ! $result ) {
		return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie check failed' ), array( 'status' => 403 ) );
	}

	// Send a refreshed nonce in header.
	rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );

	return true;
}

常见问题

FAQs
查看更多 >