Skip to content

Instantly share code, notes, and snippets.

@leehambley
Created February 9, 2021 08:36
Show Gist options
  • Save leehambley/e4c2b3d1c991c23b7769bd18e24bfb49 to your computer and use it in GitHub Desktop.
Save leehambley/e4c2b3d1c991c23b7769bd18e24bfb49 to your computer and use it in GitHub Desktop.

Create users on a KeyCloak instance

The KeyCloak REST API only allows mass insertion of the users at the Realm initialization time.

Creating users on the REST API is pretty well documented, but painful enough that it took a couple of hours to muddle through the reqired options to make this script do the right thing:

  • Create the user
  • Add them to a group
  • Send the password (re)set email

The script reads email addresses from standard in, so you can use it like this:

echo "user@example.com" | bash create-users.sh

or, feed it with a file of email addresses one per line (assumes unix line endings):

cat all-the-new-users.txt | bash create-users.sh
#!/usr/bin/env bash
REALM="********"
GROUP_NAME="********"
ADMINUSERNAME="********"
ADMINPASSWORD="********"
KEYCLOAK_BASE_URL="https://example.com"
#
# Get Auth Token
#
ACCESS_TOKEN=$(curl -s --data "username=$ADMINUSERNAME&password=$ADMINPASSWORD&grant_type=password&client_id=admin-cli" \
$KEYCLOAK_BASE_URL/auth/realms/master/protocol/openid-connect/token | jq -r .access_token)
while IFS='$\n' read -r EMAILADDR; do
echo "Creating user $EMAILADDR"
# https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_userrepresentation
RESPONSE=$(curl "$KEYCLOAK_BASE_URL/auth/admin/realms/$REALM/users" \
-s -i -k \
-H "Content-Type: application/json" \
-H "Authorization: bearer ${ACCESS_TOKEN}" \
--data "{\"username\":\"$EMAILADDR\",\"email\":\"$EMAILADDR\",\"enabled\":\"true\",\"emailVerified\":\"true\",\"groups\":[\"$GROUP_NAME\"]}");
HEADERS=$(sed -n '1,/^\r$/p' <<<"$RESPONSE");
LOCATION=$(grep -oiP 'Location: \K.*' <<<"$HEADERS");
USERUUID=$(echo ${LOCATION##*/} | tr -d '\r'); # extract the last part of the location header to get user uuid
echo "Sending password reset for $EMAILADDR ($USERUUID)";
RESPONSE=$(curl "$KEYCLOAK_BASE_URL/auth/admin/realms/$REALM/users/$USERUUID/execute-actions-email" \
-s -i -k \
-X PUT \
-H "Content-Type: application/json" \
-H "Authorization: bearer ${ACCESS_TOKEN}" \
--data "[\"UPDATE_PASSWORD\"]")
echo "done OK";
done < "${1:-/dev/stdin}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment