keycloak.py 5.69 KB
Newer Older
1
2
3
4
5
6
import requests
import os

KEYCLOAK_SERVICE = os.getenv('KEYCLOAK_SERVICE')
KEYCLOAK_REALM_NAME = os.getenv('KEYCLOAK_REALM_NAME')
KEYCLOAK_ADMIN_PASSWORD = os.getenv('KEYCLOAK_ADMIN_PASSWORD')
7
8
9
10
11

env_dict = dict(os.environ)
dict_key = env_dict.keys()
secret_names = []
secret_dict = {}
12

13

14
def get_token():
Maksimelyan Tamashevich (EPAM)'s avatar
Maksimelyan Tamashevich (EPAM) committed
15
    url = KEYCLOAK_SERVICE + '/realms/master/protocol/openid-connect/token'
16
17
18
    params = {
        'client_id': 'admin-cli',
        'grant_type': 'password',
19
        'username': 'user',
20
21
        'password': KEYCLOAK_ADMIN_PASSWORD
    }
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

    request = requests.post(url, params)

    # Check connectivity to Keycloak
    try:
        request.raise_for_status()
    except requests.exceptions.HTTPError as errh:
        raise SystemExit(f"Http Error:{errh}")
    except requests.exceptions.ConnectionError as errc:
        raise SystemExit(f"Error Connecting:{errc}")
    except requests.exceptions.Timeout as errt:
        raise SystemExit(f"Timeout Error:{errt}")
    except requests.exceptions.RequestException as err:
        raise SystemExit(f"Oops: Something Else{err}")

    return request.json()['access_token']
38

39

40
41
42
43
def create_realm():
    url = KEYCLOAK_SERVICE + '/auth/admin/realms'
    headers = {
        'content-type': 'application/json',
44
        'Authorization': 'Bearer ' + str(token)
45
    }
46
47
48
49
50
51
52
    params = {
        "id": KEYCLOAK_REALM_NAME,
        "realm": KEYCLOAK_REALM_NAME,
        "displayName": KEYCLOAK_REALM_NAME + " Realm",
        "accessTokenLifespan": 3600,
        "enabled": True
    }
53
    request = requests.post(url, headers=headers, json=params)
54

55

56
# Check existing realm or create if it's no exist
57
58
59
60
def realm():
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/'
    headers = {
        'content-type': 'application/json',
61
        'Authorization': 'Bearer ' + str(token)
62
    }
63
64
    request = requests.get(url, headers=headers)
    realms_list = []
65

66
67
    for field in request.json():
        realms_list.append(field['id'])
68

69
70
    if KEYCLOAK_REALM_NAME in realms_list:
        print(f"Realm {KEYCLOAK_REALM_NAME} already exists")
71
72
    else:
        create_realm()
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
        print(f"Creating {KEYCLOAK_REALM_NAME} realm")


def create_client(client_name, client_secret):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + KEYCLOAK_REALM_NAME + '/clients'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    params = {
        "clientId": client_name,
        "name": client_name,
        "secret": client_secret,
        "authorizationServicesEnabled": True,
        "standardFlowEnabled": False,
        "serviceAccountsEnabled": True,
        "directAccessGrantsEnabled": True,
        "enabled": True,
    }
    request = requests.post(url, headers=headers, json=params)

    return request


def get_client_id(client_name):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + KEYCLOAK_REALM_NAME + '/clients/'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    request = requests.get(url, headers=headers)
    for field in request.json():
        if field['name'] == client_name:
            client_id = field['id']
    return client_id


def get_sa_id(client_name):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + KEYCLOAK_REALM_NAME + \
        '/clients/' + get_client_id(client_name) + '/service-account-user'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    request = requests.get(url, headers=headers)

    return request.json()['id']


def update_sa(client_name):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + \
        KEYCLOAK_REALM_NAME + '/users/' + get_sa_id(client_name)
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    params = {
        "email": client_name + "@service.local",
        "enabled": True
    }
    request = requests.put(url, headers=headers, json=params)


def get_password(client_name):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + KEYCLOAK_REALM_NAME + \
        '/clients/' + get_client_id(client_name) + '/client-secret'
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    request = requests.get(url, headers=headers)

    return request.json()
146
147


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def update_password(client_secret):
    url = KEYCLOAK_SERVICE + '/auth/admin/realms/' + \
        KEYCLOAK_REALM_NAME + '/clients/' + get_client_id(client_name)
    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + str(token)
    }
    params = {
        "secret": client_secret
    }
    request = requests.put(url, headers=headers, json=params)
    print("Password was updated.")


for dict_key in env_dict:
    if dict_key.startswith('KEYCLOAK_') and dict_key.endswith('_SECRET'):
        secret_names.append(dict_key)

for secret in secret_names:
    secret_split = secret.split('_')
    secret_name = secret_split[1:len(secret_split)-1]
    if len(secret_name) != 1:
        new_secret_name = ('-'.join(secret_name))
        secret_dict[new_secret_name.lower()] = env_dict[secret]
    else:
        new_secret_name = (''.join(secret_name))
        secret_dict[new_secret_name.lower()] = env_dict[secret]

token = get_token()

178
179
realm()

180
181
182
183
184
185
186
187
188
189
for client_name, client_secret in secret_dict.items():
    if not create_client(client_name, client_secret).text:
        create_client(client_name, client_secret)
        update_sa(client_name)
        print(f"Creating {client_name} client")
    else:
        print(f"Client {client_name} already exists")

    if client_secret == get_password(client_name)['value']:
        print("Password is the same as it was.")
190
    else:
191
        update_password(client_secret)