WP REST API Login

962 Views Asked by At

Our Company makes use of multiple websites that are running on different platforms and databases (Mostly WordPress). I am trying to build integration between these websites.

If a user logs in to their account on one of our websites an automated login needs to occur on our other websites.

To accomplish this I am trying to make use of the WordPress API:

add_action('rest_api_init', function(){
    register_rest_route(
        'odp-api/v1',
        '/universal-login',
        array(
            'methods' => 'POST',
            'callback' => 'universal_login'
        )
    );
});
function universal_login(WP_REST_Request $request){
    $feedback = array();
    $posted = $request->get_body_params();

    if(isset($posted['user_login']) && isset($posted['user_password'])){
        $posted['remember'] = (isset($posted['remember']) ? $posted['remember']: 0);

        $user = wp_signon($posted, is_ssl());

        if(!is_wp_error($user)){
            $feedback['success'] = 'Success';
        } else{
            $feedback['error'] = $user->get_error_message();
        }
    } else{
        $feedback['error'] = 'Invalid account credentials.';
    }

    return $feedback;
}

The above action and function registers a custom API route, which I call in the following way:

$response = wp_safe_remote_post(
                ODP_UNIVERSAL_URL . 'wp-json/odp-api/v1/universal-login',
                array(
                    'method' => 'POST',
                    'body' => array(
                        'user_login' => $user_login,
                        'user_password' => $user_password,
                        'remember' => (isset($_POST['rememberme']) && $_POST['rememberme'] === 'forever' ? 1 : 0)
                    )
                )
            );

I get the $feedback success message and can access the just logged in user data, but when visiting the website it's clear that I/the user has in fact not been logged in.

From what I've found online it seems to be related to either the COOKIE_DOMAIN definition, or something with NONCE verification.

Why is the user being fetched successfully, remotely, but not logged in?

Is there a simpler way to log a user in remotely with WordPress?

The idea is to be able to log in from one WordPress installation, and automatically be logged in to another WordPress installation on a different domain. All our websites are running over SSL encryption.

0

There are 0 best solutions below