wp_generate_auth_cookie()
Generates authentication cookie contents.
Pluggable function — this function can be replaced from a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.
Function replacement (override) — in must-use or regular plugin you can create a function with the same name, then it will replace this function.
Hooks from the function
Return
String
. Authentication cookie contents. Empty string if user does not exist.
Usage
wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
- $user_id(int) (required)
- User ID.
- $expiration(int) (required)
- The time the cookie expires as a UNIX timestamp.
- $scheme(string)
- The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
Default: 'auth' - $token(string)
- User's session token to use for this cookie.
Default: ''
Changelog
Since 2.5.0 | Introduced. |
Since 4.0.0 | The $token parameter was added. |
wp_generate_auth_cookie() wp generate auth cookie code WP 6.8
function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) { $user = get_userdata( $user_id ); if ( ! $user ) { return ''; } if ( ! $token ) { $manager = WP_Session_Tokens::get_instance( $user_id ); $token = $manager->create( $expiration ); } if ( str_starts_with( $user->user_pass, '$P$' ) || str_starts_with( $user->user_pass, '$2y$' ) ) { // Retain previous behaviour of phpass or vanilla bcrypt hashed passwords. $pass_frag = substr( $user->user_pass, 8, 4 ); } else { // Otherwise, use a substring from the end of the hash to avoid dealing with potentially long hash prefixes. $pass_frag = substr( $user->user_pass, -4 ); } $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme ); $hash = hash_hmac( 'sha256', $user->user_login . '|' . $expiration . '|' . $token, $key ); $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash; /** * Filters the authentication cookie. * * @since 2.5.0 * @since 4.0.0 The `$token` parameter was added. * * @param string $cookie Authentication cookie. * @param int $user_id User ID. * @param int $expiration The time the cookie expires as a UNIX timestamp. * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'. * @param string $token User's session token used. */ return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token ); }