File: setup_keycloak_client.py

package info (click to toggle)
keystone 2%3A28.0.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,428 kB
  • sloc: python: 125,079; pascal: 2,239; sh: 877; xml: 335; makefile: 216
file content (64 lines) | stat: -rw-r--r-- 1,906 bytes parent folder | download | duplicates (2)
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
import os
import requests

KEYCLOAK_USERNAME = os.environ.get('KEYCLOAK_USERNAME')
KEYCLOAK_PASSWORD = os.environ.get('KEYCLOAK_PASSWORD')
KEYCLOAK_URL = os.environ.get('KEYCLOAK_URL')
HOST_IP = os.environ.get('HOST_IP', 'localhost')


class KeycloakClient:
    def __init__(self):
        self.session = requests.session()

    @staticmethod
    def construct_url(realm, path):
        return f'{KEYCLOAK_URL}/admin/realms/{realm}/{path}'

    @staticmethod
    def token_endpoint(realm):
        return f'{KEYCLOAK_URL}/realms/{realm}/protocol/openid-connect/token'

    def _admin_auth(self, realm):
        params = {
            'grant_type': 'password',
            'client_id': 'admin-cli',
            'username': KEYCLOAK_USERNAME,
            'password': KEYCLOAK_PASSWORD,
            'scope': 'openid',
        }
        r = requests.post(self.token_endpoint(realm), data=params).json()
        headers = {
            'Authorization': f"Bearer {r['access_token']}",
            'Content-Type': 'application/json',
        }
        self.session.headers.update(headers)
        return r

    def create_client(self, realm, client_id, client_secret, redirect_uris):
        self._admin_auth(realm)
        data = {
            'clientId': client_id,
            'secret': client_secret,
            'redirectUris': redirect_uris,
            'implicitFlowEnabled': True,
            'directAccessGrantsEnabled': True,
        }
        return self.session.post(
            self.construct_url(realm, 'clients'), json=data
        )


def main():
    c = KeycloakClient()

    redirect_uris = [
        f'http://{HOST_IP}/identity/v3/auth/OS-FEDERATION/identity_providers/sso/protocols/openid/websso',
        f'http://{HOST_IP}/identity/v3/auth/OS-FEDERATION/websso/openid',
    ]

    c.create_client('master', 'devstack', 'nomoresecret', redirect_uris)


if __name__ == "__main__":
    main()