wp_authenticate_cookie()
云策文档标注
概述
wp_authenticate_cookie() 是 WordPress 中用于通过认证 Cookie 验证用户身份的函数。它作为 'authenticate' 过滤器的一部分,优先处理 Cookie 认证,并在用户名和密码为空时检查有效 Cookie。
关键要点
- 函数参数:$user(WP_User|WP_Error|null,默认 null),$username(string,非空时取消 Cookie 认证),$password(string,非空时取消 Cookie 认证)。
- 返回值:成功时返回 WP_User 对象,失败时返回 WP_Error 对象。
- 核心逻辑:如果 $user 已是 WP_User 实例则直接返回;当用户名和密码为空时,调用 wp_validate_auth_cookie() 验证 Cookie,成功则创建 WP_User,失败则根据 $auth_secure_cookie 检查 Cookie 是否过期。
- 注意事项:Cookie 未设置时函数保持静默,不返回错误。
代码示例
function wp_authenticate_cookie(
$user,
$username,
#[SensitiveParameter]
$password
) {
global $auth_secure_cookie;
if ( $user instanceof WP_User ) {
return $user;
}
if ( empty( $username ) && empty( $password ) ) {
$user_id = wp_validate_auth_cookie();
if ( $user_id ) {
return new WP_User( $user_id );
}
if ( $auth_secure_cookie ) {
$auth_cookie = SECURE_AUTH_COOKIE;
} else {
$auth_cookie = AUTH_COOKIE;
}
if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
}
// If the cookie is not set, be silent.
}
return $user;
}
原文内容
Authenticates the user using the WordPress auth cookie.
Parameters
Source
function wp_authenticate_cookie(
$user,
$username,
#[SensitiveParameter]
$password
) {
global $auth_secure_cookie;
if ( $user instanceof WP_User ) {
return $user;
}
if ( empty( $username ) && empty( $password ) ) {
$user_id = wp_validate_auth_cookie();
if ( $user_id ) {
return new WP_User( $user_id );
}
if ( $auth_secure_cookie ) {
$auth_cookie = SECURE_AUTH_COOKIE;
} else {
$auth_cookie = AUTH_COOKIE;
}
if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
}
// If the cookie is not set, be silent.
}
return $user;
}
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |