How to transition cookies from .subdomain.domain.com to .domain.com with minimal impact on users?

I need to extend the cookies of a subdomain.domain.com to all of the domain.com’s subdomains (.domain.com in cookie terms).

I am trying to minimize the impact of this transition. It seems that flipping the switch with define('COOKIE_DOMAIN', '.domain.com'); in wp-config leaves the user in a state of limbo — their cookie is good enough to validate, so it won’t move to the new domain scope.

Read More

Any ideas on how I can transition cookies from .subdomain.domain.com to .domain.com with minimal impact on users?

Here’s the code I’ve been failing and flailing with. It attempts to validate the old cookies when a bad hash is detected (from changing AUTH_KEY in wp-config.php) and then tries to re-validate and send them back to where they came from:

function do_report_bad_hash( $cookie_elements ) {

    if( isset( $_COOKIE['wordpress_logged_in_'] ) ) {
        $user_id = wp_validate_auth_cookie( urldecode( $_COOKIE['wordpress_logged_in_']), 'logged_in' );

        setcookie( 'wordpress_logged_in_', '', 0, '/', '.subdomain.domain.com', false, true ); 
        unset( $_COOKIE['wordpress_logged_in_'] );

        setcookie( 'wordpress_', '', 0, '/', '.subdomain.domain.com', false, true ); 
        unset( $_COOKIE['wordpress_'] );

        if ( $user_id !== false ) {

            wp_set_auth_cookie($user_id);

            $redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            header("Location: $redirect");    

        }

    } 

}
add_action('auth_cookie_bad_hash', 'do_report_bad_hash', 11, 1 );

Related posts

Leave a Reply

1 comment

  1. This answer may help. To quote:

    The basic code you need here is this in the wp-config file:

    define('LOGGED_IN_COOKIE', 'login_cookie_name');
    define('AUTH_COOKIE','auth_cookie_name');
    define('COOKIE_DOMAIN', '.example.com');
    define('COOKIEHASH', 'random_hash_here');
    

    Put that in the config across multiple sites, set the keys and salts to be the same, and you’ll have login cookies that work across the domain and subdomains.