This repository has been archived by the owner on Dec 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.py
55 lines (39 loc) · 1.77 KB
/
client.py
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
import codecs
import json
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from .config import Config
class Client(object):
def __init__(self, config=None):
if not config:
config = Config()
self.config = config
def client_credentials_flow(self):
data = {'grant_type': 'client_credentials'}
return self.token_flow(data, auth_basic=True)
def token_flow(self, data, auth_basic=None, path='/protocol/openid-connect/token', url=None):
opts = {
'url': url or self.config.realm_url + path,
}
if not isinstance(data, bytes):
if not isinstance(data, str):
data = urlencode(data)
data = data.encode()
if 'headers' not in opts:
opts['headers'] = {}
if 'Content-Type' not in opts['headers']:
opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
if 'X-Client' not in opts['headers']:
opts['headers']['X-Client'] = 'keycloak-python'
if auth_basic:
if isinstance(auth_basic, bool):
if not self.config.client_id or not self.config.secret:
raise Exception('auth_basic: No client_id or secret given.')
auth_str = self.config.client_id + ":" + self.config.secret
else:
# assume it's "user:pass"
auth_str = auth_basic
# codecs.encode does only work with bytes, is using utf8 encoded string right?
encoded_auth_str = codecs.encode(auth_str.encode(), 'base64').decode('ascii').rstrip('\n')
opts['headers']['Authorization'] = 'Basic ' + encoded_auth_str
return json.loads(urlopen(Request(**opts), data).read().decode())