Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rmpel/49e0da2d978f5d2869c9bc58b4552306 to your computer and use it in GitHub Desktop.
Save rmpel/49e0da2d978f5d2869c9bc58b4552306 to your computer and use it in GitHub Desktop.
WORDPRESS REST API - Login a user during a rest call - incompatible with caching
<?php
/**
* Maybe login by cookie.
* This function will log in a user by their authentication cookie, if they have one.
* This will use a full authentication, so it is safe from cookie-faking.
* Cookie hijacking is still a possibility, however, that's a WordPress issue, not a plugin issue.
* (To combat this; prefix the salts in wp-config.php with $_SERVER['REMOTE_ADDR']. This is not watertight,
* but always better than not)
*
* Call this function in your `permission_callback`, or in case of `__return_true` in your `callback` for getting items.
* After that, you can use `current_user_can` etc.
*/
add_filter( 'rest_request_before_callbacks', 'example_maybe_login_by_cookie' );
/**
* Maybe log in a user by their authentication cookie.
*
* @param \WP_REST_Response $passthru Passing through the response
*
* @return void
*/
function example_maybe_login_by_cookie( $passthru ) {
// Do not mess with an existing user. Impossible in a REST call, but prevents multiple actions taken.
if ( is_user_logged_in() ) {
return;
}
// Find cookie starting with 'wordpress_logged_in_'.
$cookie_name = null;
foreach ( $_COOKIE as $key => $value ) {
if ( str_starts_with( $key, 'wordpress_logged_in_' ) ) {
$cookie_name = $key;
break;
}
}
// No cookie found, we cannot log in.
if ( ! $cookie_name ) {
return;
}
// Validate the cookie.
$user_id = wp_validate_auth_cookie( $_COOKIE[ $cookie_name ], 'logged_in' );
if ( ! $user_id || is_wp_error( $user_id ) ) {
return;
}
// Log in the user.
wp_set_current_user( $user_id );
return $passthru;
}
@Jikizuari
Copy link

add_filter( 'rest_request_before_callbacks', 'example_maybe_login_by_cookie', 10, 1 );

This filter will make this automatic for every REST request.

@rmpel
Copy link
Author

rmpel commented Mar 27, 2025

Great suggestion, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment