DEV Community

Cover image for Simple health check for Keycloak
Ulrich VACHON
Ulrich VACHON

Posted on

Simple health check for Keycloak

Today we will see how to add a simple and not intrusive health check based on shell script for your Keycloak

Sometime ago I did the (bad) experience to note the user sessions increase very faster without known reason on the main cluster.

The result of this was a rise of the user sessions which keep busy the CPU because we reached the maximum of heap memory occupation. More of 50k user sessions have been created on a dedicated Keycloak client by a health check probe a bit chatty 😇

Lesson of the day, if you fine-tuned your token settings don't forget to login AND logout test users.

A simple probe

The only prerequisite is to have jq command available on the environment where the script runs.

#!/bin/bash

login_access=$(curl -k -X POST \
   -H "Content-Type:application/x-www-form-urlencoded" \
   -d "grant_type=password" \
   -d "client_id=admin-cli" \
   -d "username=alive" \
   -d "password=[REDACTED]" \
 'https://keyclaok.company.com/auth/realms/[REALM]/protocol/openid-connect/token')

error=$(jq -r .error <<< $login_access)

if [ $error == "null" ]; then
    echo "Login successful for test user."
else
    echo "Unable to login test user ($error)."
    exit 1
fi

access_token=$(jq -r  '.access_token' <<< "${login_access}")
refresh_token=$(jq -r  '.refresh_token' <<< "${login_access}")

logout_response=$(curl -s -o /dev/null -w '%{http_code}' -k -X POST \
   -H "Content-Type:application/x-www-form-urlencoded" \
   -H "Authorization: Bearer $access_token" \
   -d "client_id=[CLIENT_ID]" \
   -d "refresh_token=$refresh_token" \
 'https://keycloak.company.com/auth/realms/[REALM]/protocol/openid-connect/logout')

if [ $logout_response -eq 204 ]; then
    echo "Logout successful for test user."
else
    echo "Unable to logout test user ($logout_response)."
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

Le me try it

https://gist.github.com/ulrich/aa04a793d54703998ecb015a0e2ff803

Crédit photo : https://pixabay.com/fr/users/jackmac34-483877/

Top comments (0)