返回介绍

rest_cookie_check_errors()

发布于 2017-09-11 10:10:47 字数 2820 浏览 1083 评论 0 收藏 0

rest_cookie_check_errors( WP_Error|mixed $result )

Checks for errors when using cookie-based authentication.


description

WordPress’ built-in cookie authentication is always active for logged in users. However, the API has to check nonces for each request to ensure users are not vulnerable to CSRF.


参数

$result

(WP_Error|mixed) (Required) Error from another authentication handler, null if we should handle it, or another value if not.


返回值

(WP_Error|mixed|bool) WP_Error if the cookie is invalid, the $result, otherwise true.


源代码

File: wp-includes/rest-api.php

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

	global $wp_rest_auth_cookie, $wp_rest_server;

	/*
	 * 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 nonce is invalid' ), array( 'status' => 403 ) );
	}

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

	return true;
}

更新日志

Versiondescription
4.4.0Introduced.

相关函数

Uses

  • wp-includes/rest-api/class-wp-rest-server.php: WP_REST_Server::send_header()
  • wp-includes/l10n.php: __()
  • wp-includes/pluggable.php: wp_verify_nonce()
  • wp-includes/pluggable.php: wp_create_nonce()
  • wp-includes/pluggable.php: is_user_logged_in()
  • wp-includes/pluggable.php: wp_set_current_user()
  • wp-includes/class-wp-error.php: WP_Error::__construct()
  • Show 2 more uses Hide more uses

User Contributed Notes

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文