WP set auth cookie using Ajax is not saved to browser

We are creating an external dashboard that uses WordPress data, obviously, we use WP REST API v2

We want total separation from the traditional WP Dashboard, but we also want to log in user “behind the scenes” to WP Admin Dashboard, so we can redirect user to some plugin admin UI pages; due to limitation of the WP REST API

This is what we did, we created a custom plugin that has the function createAuthkey below that does Logins in user then creates a key (token).

The important part we care about is if the login succeeds (wp_authenticate()), we want also to save the wp_auth_cookie on the browser, so even if the user is not directly logged into /wp-admin, if now the browser enters WP admin pages, we want them to be logged in and therefore we use wp_set_auth_cookie(), but the AJAX response DOES NOT save the returned cookie in the browser resources (but correctly returns it in response) and therefore when the user is redirected to WP admin page, they are logged out

function createAuthKey( WP_REST_Request $request )
{
    // Get login information
    $username   = $request->get_param( 'username' );
    $password   = $request->get_param( 'password' );

    $user = wp_authenticate( $username, $password );

    if ( is_wp_error( $user ) ) {
     return false;
    }

    $converter = new Encryption;
    $encoded = $converter->encode($username . ":" . $password);

    // Set Cookie: NOT SAVED TO BROWSER!!!
    wp_set_auth_cookie($user->ID, true);

    return ['key' => $encoded, 'cookie' => $_COOKIE];
}

1 Answer
1

I assume that your custom dashboard is on a different domain/subdomain than the WordPress installation. Cookies can only be set for the current domain.

Typically cookies will not work cross domain. So your dashboard cannot create a cookie for the WordPress website. Theoretically it’s possible to bypass with some server configurations, but this technique has to be supported by the users browser.

Leave a Comment