Forked from nickbabkin/get-keycloak-active-sessions.py
Created
July 25, 2024 17:10
-
-
Save xgp/a20b2c8d39dcd1f995e701f2e8cbf8fc to your computer and use it in GitHub Desktop.
Get total number of active Keycloak sessions per client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
USAGE: | |
1) Create client in Keycloak and enable client authentication + service account roles for it | |
2) Assign "view-realm" role from realm-management client on "service account roles" tab for the client | |
3) Replace keycloak_url and realm_name variables with your Keycloak base dir | |
4) Export client credentials into $CLIENTID and CLIENTSECRET env variable | |
5) python get-keycloak-active-sessions.py | |
''' | |
import requests | |
import json | |
import os | |
keycloak_url = "https://keycloak" | |
realm = "realm" | |
client_id = os.getenv('CLIENTID') | |
client_secret = os.getenv('CLIENTSECRET') | |
grant_type = "client_credentials" | |
auth_url = f"{keycloak_url}/auth/realms/{realm}/protocol/openid-connect/token" | |
headers = {"Content-Type": "application/x-www-form-urlencoded"} | |
data = {"grant_type": grant_type, "client_id": client_id, "client_secret": client_secret} | |
response = requests.post(auth_url, headers=headers, data=data) | |
token = response.json()["access_token"] | |
api_url = f"{keycloak_url}/auth/admin/realms/{realm}/client-session-stats" | |
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} | |
response = requests.get(api_url, headers=headers) | |
data=response.content.decode("utf-8") | |
json_data = json.loads(data) | |
for item in json_data: | |
print(item["clientId"], item["active"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment