我们正在创建一个使用Wordpress数据的外部仪表板,显然,我们使用WP REST API v2
我们希望与传统的WP仪表板完全分离,但我们也希望将用户“幕后”登录到WP管理仪表板,所以we can redirect user to some plugin admin UI pages; due to limitation of the WP REST API
这就是我们所做的,我们创建了一个自定义插件,下面有createAuthkey函数,可以登录用户,然后创建一个密钥(令牌)。
我们关心的重要部分是,如果登录成功(wp\\u authenticate()),我们还希望在浏览器上保存wp\\u auth\\u cookie,因此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 因此,我们使用wp\\u set\\u auth\\u cookie(),但AJAX响应DOES NOT save the returned cookie in the browser resources (but correctly returns it in response) 因此,当用户重定向到WP admin页时,他们将注销
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];
}