Secure Session Token Management with WP_Http_Cookie

Last updated 1 month ago

PHP
function set_user_session_token() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $session_token = hash('sha256', $user_id . AUTH_KEY . time());

        $cookie = new WP_Http_Cookie(array(
            'name'     => 'user_session_token',
            'value'    => $session_token,
            'expires'  => time() + HOUR_IN_SECONDS,
            'secure'   => true,
            'httponly' => true,
            'path'     => '/',
        ));

        // Set the secure session cookie.
        wp_remote_get(home_url(), array('cookies' => array($cookie)));
    }
}

add_action('wp_login', 'set_user_session_token');

function verify_user_session_token($token) {
    return (isset($_COOKIE['user_session_token']) && $_COOKIE['user_session_token'] === $token);
}

All code snippets are licensed GPLv2 or later unless otherwise stated.