函数文档

wp_validate_application_password()

💡 云策文档标注

概述

wp_validate_application_password() 函数用于验证通过基本认证传递的应用密码凭证。它检查应用密码的可用性,并尝试使用提供的用户名和密码进行身份验证。

关键要点

  • 参数 $input_user 可以是用户 ID 或 false,表示已确定的用户或未确定状态。
  • 返回值为成功认证的用户 ID 或 false,表示认证失败。
  • 函数首先避免重复认证,如果 $input_user 非空则直接返回。
  • 检查应用密码是否全局可用,通过 wp_is_application_passwords_available() 函数。
  • 要求 $_SERVER['PHP_AUTH_USER'] 和 $_SERVER['PHP_AUTH_PW'] 必须同时设置才能尝试认证。
  • 使用 wp_authenticate_application_password() 进行实际认证,返回 WP_User 对象则提取其 ID。
  • 如果认证失败,返回原始的 $input_user 值。

代码示例

function wp_validate_application_password( $input_user ) {
    // Don't authenticate twice.
    if ( ! empty( $input_user ) ) {
        return $input_user;
    }

    if ( ! wp_is_application_passwords_available() ) {
        return $input_user;
    }

    // Both $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] must be set in order to attempt authentication.
    if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
        return $input_user;
    }

    $authenticated = wp_authenticate_application_password( null, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );

    if ( $authenticated instanceof WP_User ) {
        return $authenticated->ID;
    }

    // If it wasn't a user what got returned, just pass on what we had received originally.
    return $input_user;
}

注意事项

  • 此函数依赖于 $_SERVER 超全局变量中的 PHP_AUTH_USER 和 PHP_AUTH_PW,确保它们已正确设置。
  • 应用密码功能需通过 wp_is_application_passwords_available() 检查是否启用。
  • 认证失败时,函数返回原始输入,避免中断其他认证流程。

📄 原文内容

Validates the application password credentials passed via Basic Authentication.

Parameters

$input_userint|falserequired
User ID if one has been determined, false otherwise.

Return

int|false The authenticated user ID if successful, false otherwise.

Source

function wp_validate_application_password( $input_user ) {
	// Don't authenticate twice.
	if ( ! empty( $input_user ) ) {
		return $input_user;
	}

	if ( ! wp_is_application_passwords_available() ) {
		return $input_user;
	}

	// Both $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] must be set in order to attempt authentication.
	if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
		return $input_user;
	}

	$authenticated = wp_authenticate_application_password( null, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );

	if ( $authenticated instanceof WP_User ) {
		return $authenticated->ID;
	}

	// If it wasn't a user what got returned, just pass on what we had received originally.
	return $input_user;
}

Changelog

Version Description
5.6.0 Introduced.