How we import all existing users from Wordpress to Keycloak?

I am new in Keycloak, We have a WordPress website with different user roles(Editor). Our new application is using Keycloak, so we need to import all existing users from Wordpress to Keycloak. Could you provide a solution for this?

I would be extremely grateful to get some clarity on the questions above.

Thanks!

There is a Keycloak extension which facilitates migrating users into Keycloak from another application.

It will require you to implement an endpoint on the wordpress side, but otherwise it works great. Let us know what you decide, as this is probably a use case many others have.

Thank You for the respone
It will require you to implement an endpoint on the wordpress side, but otherwise it works great. β€”> Could you please elaborate on this? How do we create these endpoints? What are all the parameters to be passed from Wordpress to the Keycloak plugin?

It’s in their documentation here: GitHub - daniel-frak/keycloak-user-migration: A Keycloak plugin for migrating users from legacy systems

I implemented the endpoints for wordpress. It works great. :ok_hand:

/* Create Custom Endpoint */
add_action('rest_api_init', 'create_keycloak_endpoints');
 
function create_keycloak_endpoints() {
    register_rest_route(
        'wp/v2',
        '/keycloak-user-migration/(?P<username>.+)',
        [
            'methods' => 'GET',
            'callback' => 'keycloak_get',
        ]
    );
    register_rest_route(
        'wp/v2',
        '/keycloak-user-migration/(?P<username>.+)',
        [
            'methods' => 'POST',
            'callback' => 'keycloak_post',
        ]
    );
}

function keycloak_get($request) {
	$username = $request['username'];
	$user = get_user_by('email', $username);
	if (!$user) {
		$user = get_user_by('login', $username);
	}
	if (!$user) {
		write_log('not found '.$username);
		return new WP_REST_Response(['message' => 'not found '.$username], 404);
	}
    return [
		'id' => $user->ID, 
		'username' => $user->user_login,
		'email' => $user->user_email,
        'firstName' => $user->user_firstname,
        'lastName' => $user->user_lastname,
		'enabled' => true,
		'emailVerified' => true,
	];
}

function keycloak_post($request) {
	$username = $request['username'];
	$password = $request['password'];
	$user = get_user_by('login', $username);
	if (!$user) {
		$user = get_user_by('email', $username);
	}
	if (!$user || !wp_check_password($password, $user->user_pass, $user->ID)) {
		write_log('wrong_password for '.$username);
		return new WP_REST_Response(['message' => 'wrong_password for '.$username], 404);
	}
	return true;
}

if (!function_exists('write_log')) {
    function write_log($log)  {
        if (is_array($log) || is_object($log)) {
            error_log(print_r($log, true));
        } else {
            error_log($log);
        }
    }
}```
2 Likes