External Authentication, session_tokens not destroyed on logout
There are many questions and answers on external authentication and some code prior to WordPress 4.0 need some tweaking to get them to work. For example, adding a fourth parameter to the wp_set_auth_cookie
will stop some strange issues. However, session_tokens are not destroyed and the meta value is repeatedly added to after each login (leading to a huge mess).
To get WordPress caching plugins to work properly, then the session_tokens need to work properly: created on login and destroyed on logout.
The following code will login any user in the external database.
add_action( 'after_setup_theme', 'xenword_login', 10, 1 );
function xenword_login( $username ) {
add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); // hook in earlier than other callbacks to short-circuit them
$user = wp_signon( array( 'user_login' => $username ) );
remove_filter( 'authenticate', 'allow_programmatic_login', 10 );
if ( is_a( $user, 'WP_User' ) ) {
wp_clear_auth_cookie();
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true, is_ssl(), true );
if ( is_user_logged_in() ) {
return $user->ID;
}
}
return false;
}
Then an allow_programmatic_login is placed in the same file.
function allow_programmatic_login( $user, $username, $password ) {
$visitor = XenWord::getVisitor();
$user_id = XenWord::getVisitor()->getUserId();
if ( $user_id > 0 ) {
$username = $visitor['username'];
return get_user_by( 'login', $username );
}
}
Fantastic except an administrator, editor, etc cannot go to the dashboard because the cookie will not be validated. Replacing the wp_validate_auth_cookie
will get the accounts to have access but then caching plugins will not load properly.
After tinkering for a few days (year), I discovered recently that the verify( $token )
causes the issue.
$manager = WP_Session_Tokens::get_instance( $user->ID );
if ( ! $manager->verify( $token ) ) {
do_action( 'auth_cookie_bad_session_token', $cookie_elements );
return false;
}
This led me to look at the database and see that the session_tokens were being created on login but not destroyed on logout.
My question: Has anyone identified and overcome this issue because simply using the following logs in the account but no session_tokens are created.
wp_clear_auth_cookie();
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id, true, is_ssl(), true );
do_action('wp_login', $user->user_login );
This leaves me using the authenticate option but the session_tokens are not destroyed. Any suggestions?
Leave an answer