summaryrefslogtreecommitdiff
path: root/devstack/tools/oidc/setup_keycloak_client.py
blob: 15fa37b41f2b7327a56848a6c431a6c63e430b46 (plain)
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
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(object):
    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': ("Bearer %s" % 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()