-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeycloak-add-clients.sh
executable file
·83 lines (71 loc) · 2.2 KB
/
keycloak-add-clients.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash
# Colorize terminal
red='\e[0;31m'
no_color='\033[0m'
# Default
KC_USERNAME="admin"
# Declare script helper
TEXT_HELPER="\nThe purpose of this script is to create multiple clients in a Keycloak realm.
Following flags are available:
-c JSON array of client configurations.
-k Keycloak host.
-p Keycloak password.
-r Keycloak realm where to add the clients.
-u Keycloak username (Default is '$KC_USERNAME').
-h Print script help.\n\n"
print_help() {
printf "$TEXT_HELPER"
}
# Parse options
while getopts hc:k:p:r:u: flag; do
case "${flag}" in
c)
KC_CLIENTS=${OPTARG};; # Expecting a JSON array
k)
KC_HOST=${OPTARG};;
p)
KC_PASSWORD=${OPTARG};;
r)
KC_REALM=${OPTARG};;
u)
KC_USERNAME=${OPTARG};;
h | *)
print_help
exit 0;;
esac
done
if [ -z "$KC_HOST" ]; then
printf "\n${red}Error.${no_color} Argument missing: keycloak host (flag -k)."
exit 1
elif [ -z "$KC_PASSWORD" ]; then
printf "\n${red}Error.${no_color} Argument missing: admin password (flag -p)."
exit 1
elif [ -z "$KC_REALM" ]; then
printf "\n${red}Error.${no_color} Argument missing: keycloak realm (flag -r)."
exit 1
elif [ -z "$KC_CLIENTS" ]; then
printf "\n${red}Error.${no_color} Argument missing: client configurations (flag -c)."
exit 1
fi
ACCESS_TOKEN=$(curl -fsSL \
-X POST "$KC_HOST/realms/master/protocol/openid-connect/token" \
-d "client_id=admin-cli" \
-d "username=$KC_USERNAME" \
-d "password=$KC_PASSWORD" \
-d "grant_type=password" | jq -r '.access_token')
for CLIENT in $(echo "$KC_CLIENTS" | jq -c '.[]'); do
CLIENT_ID=$(echo "$CLIENT" | jq -r '.clientId')
curl -fsSL \
-X POST "$KC_HOST/admin/realms/$KC_REALM/clients" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-d "$CLIENT"
CLIENT_UUID=$(curl -fsSL \
-X GET "$KC_HOST/admin/realms/$KC_REALM/clients?clientId=$CLIENT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" | jq -r '.[0].id')
if [ "$CLIENT_UUID" != "null" ]; then
printf "\nClient '$CLIENT_ID' created successfully in realm '$KC_REALM'.\n"
else
printf "\n${red}Error.${no_color} Failed to create client '$CLIENT_ID'.\n"
fi
done