File size: 2,461 Bytes
64ab846
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import logging
from keycloak import KeycloakOpenID
import json


class KeycloakAuthenticator:

    def __init__(self, configuration):

        with open(configuration, 'r') as f:
            kc_params = json.load(f)

        self.status_ok = True
        self.log = logging.getLogger()
        # self.log.info("Starting Keycloak Authenticator")

        self.keycloak_server_url = kc_params['server_url']
        self.keycloak_realm_name = kc_params['realm_name']
        self.keycloak_client_id = kc_params['client_id']
        # self.keycloak_client_secret = "joao123"  # Omitted since public client

        # Keycloak user :
        self.keycloak_username = kc_params['username']
        self.keycloak_password = kc_params['password']

        # Start OpenID connection without client_secret
        self.keycloak_openid = KeycloakOpenID(
            server_url=self.keycloak_server_url,
            realm_name=self.keycloak_realm_name,
            client_id=self.keycloak_client_id  # No client_secret_key for public client
        )

        # Get WellKnown configuration
        try:
            self.log.debug("Getting wellKnown configuration...")
            self.keycloak_config_well_known = self.keycloak_openid.well_known()  # Correct method
            self.log.debug(self.keycloak_config_well_known)
        except Exception as ex:
            self.log.error("Error getting wellKnown configuration ")
            self.log.error(ex)
            self.status_ok = False

    def get_token(self):
        if not self.status_ok:
            self.log.error("The connection has not been established. Check the logs.")
            return None
        self.log.debug("Getting token for user {}".format(self.keycloak_username))
        try:
            keycloak_token = self.keycloak_openid.token(self.keycloak_username, self.keycloak_password)
            self.log.debug("Token: {}".format(keycloak_token))
            for k in keycloak_token.keys():
                self.log.debug("{} = {}".format(k, keycloak_token[k]))
            token_value = keycloak_token['access_token']

        except Exception as ex:
            self.log.error("Error getting token")
            self.log.error(ex)
            token_value = None

        return token_value

if __name__ == '__main__':
    auth = KeycloakAuthenticator("../config/keycloak_config.json")
    token = auth.get_token()
    print(token)