Skip to content

Instantly share code, notes, and snippets.

@burnedikt
Created May 8, 2020 13:05
Show Gist options
  • Save burnedikt/4cb116766023decdd60d676359718234 to your computer and use it in GitHub Desktop.
Save burnedikt/4cb116766023decdd60d676359718234 to your computer and use it in GitHub Desktop.
Get users from keycloak
# Requires jq to be installed --> https://stedolan.github.io/jq/
# Create a suitable client supporting "Direct Auth" for your keycloak instance and remember its client credentials (id and secret)
# also see https://developers.redhat.com/blog/2020/01/29/api-login-and-jwt-token-generation-using-keycloak/
CLIENT_ID=test
CLIENT_SECRET=test-secret
USERNAME=admin
PASSWORD=supersecure
KEYCLOAK_URL=https://your.keycloak.com
REALM_NAME=realm
# Obtain a valid access token
ACCESS_TOKEN=$(curl --silent --location --request POST "${KEYCLOAK_URL}/auth/realms/${REALM_NAME}/protocol/openid-connect/token/" \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode "client_id=${CLIENT_ID}" \
--data-urlencode "client_secret=${CLIENT_SECRET}" \
--data-urlencode "username=${USERNAME}" \
--data-urlencode "password=${PASSWORD}" \
| jq -r '.access_token')
# Get the list of users
curl --verbose --location --request GET "${KEYCLOAK_URL}/auth/admin/realms/${REALM_NAME}/users" \
--header "Authorization: Bearer ${ACCESS_TOKEN}"
@burnedikt
Copy link
Author

To check which users are in Role XYZ (which is not trivially possible as the admin area only exposes direct, but not effective assignments):

# Get the list of users
USERS_RESPONSE=$(curl --silent --location --request GET "${KEYCLOAK_URL}/auth/admin/realms/${REALM_NAME}/users" \
--header "Authorization: Bearer ${ACCESS_TOKEN}")
USER_IDS=$(echo ${USERS_RESPONSE} | jq -r '.[].id')

# For each user, check the effective roles and whether it contains the desired roles
ROLE_NAME="Desired Role Name"
for userid in $USER_IDS;
do
  USER_ROLES=$(curl --silent --location --request GET "${KEYCLOAK_URL}/auth/admin/realms/${REALM_NAME}/users/${userid}/role-mappings/realm/composite" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" | jq -r ".[] | select(.name == \"${ROLE_NAME}\") | .name")
  if [[ " ${USER_ROLES[@]} " =~ " ${ROLE_NAME} " ]]; then
    USER=$(echo ${USERS_RESPONSE} | jq ".[] | select(.id == \"${userid}\") | .email")
    echo "User ${USER} has role ${ROLE_NAME}"
  fi
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment