You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1295 lines
48 KiB

7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from builtins import isinstance
  27. from typing import List, Iterable
  28. from keycloak.urls_patterns import URL_ADMIN_GROUPS_REALM_ROLES, \
  29. URL_ADMIN_GET_GROUPS_REALM_ROLES
  30. from .connection import ConnectionManager
  31. from .exceptions import raise_error_from_response, KeycloakGetError
  32. from .keycloak_openid import KeycloakOpenID
  33. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  34. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, \
  35. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  36. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  37. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  38. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  39. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, \
  40. URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  41. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  42. URL_ADMIN_USER_REALM_ROLES, URL_ADMIN_REALM
  43. class KeycloakAdmin:
  44. PAGE_SIZE = 100
  45. _server_url = None
  46. _username = None
  47. _password = None
  48. _realm_name = None
  49. _client_id = None
  50. _verify = None
  51. _client_secret_key = None
  52. _auto_refresh_token = None
  53. _connection = None
  54. _token = None
  55. _custom_headers = None
  56. _user_realm_name = None
  57. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  58. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  59. """
  60. :param server_url: Keycloak server url
  61. :param username: admin username
  62. :param password: admin password
  63. :param realm_name: realm name
  64. :param client_id: client id
  65. :param verify: True if want check connection SSL
  66. :param client_secret_key: client secret key
  67. :param custom_headers: dict of custom header to pass to each HTML request
  68. :param user_realm_name: The realm name of the user, if different from realm_name
  69. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  70. """
  71. self.server_url = server_url
  72. self.username = username
  73. self.password = password
  74. self.realm_name = realm_name
  75. self.client_id = client_id
  76. self.verify = verify
  77. self.client_secret_key = client_secret_key
  78. self.auto_refresh_token = auto_refresh_token or []
  79. self.user_realm_name = user_realm_name
  80. self.custom_headers = custom_headers
  81. # Get token Admin
  82. self.get_token()
  83. @property
  84. def server_url(self):
  85. return self._server_url
  86. @server_url.setter
  87. def server_url(self, value):
  88. self._server_url = value
  89. @property
  90. def realm_name(self):
  91. return self._realm_name
  92. @realm_name.setter
  93. def realm_name(self, value):
  94. self._realm_name = value
  95. @property
  96. def connection(self):
  97. return self._connection
  98. @connection.setter
  99. def connection(self, value):
  100. self._connection = value
  101. @property
  102. def client_id(self):
  103. return self._client_id
  104. @client_id.setter
  105. def client_id(self, value):
  106. self._client_id = value
  107. @property
  108. def client_secret_key(self):
  109. return self._client_secret_key
  110. @client_secret_key.setter
  111. def client_secret_key(self, value):
  112. self._client_secret_key = value
  113. @property
  114. def verify(self):
  115. return self._verify
  116. @verify.setter
  117. def verify(self, value):
  118. self._verify = value
  119. @property
  120. def username(self):
  121. return self._username
  122. @username.setter
  123. def username(self, value):
  124. self._username = value
  125. @property
  126. def password(self):
  127. return self._password
  128. @password.setter
  129. def password(self, value):
  130. self._password = value
  131. @property
  132. def token(self):
  133. return self._token
  134. @token.setter
  135. def token(self, value):
  136. self._token = value
  137. @property
  138. def auto_refresh_token(self):
  139. return self._auto_refresh_token
  140. @property
  141. def user_realm_name(self):
  142. return self._user_realm_name
  143. @user_realm_name.setter
  144. def user_realm_name(self, value):
  145. self._user_realm_name = value
  146. @property
  147. def custom_headers(self):
  148. return self._custom_headers
  149. @custom_headers.setter
  150. def custom_headers(self, value):
  151. self._custom_headers = value
  152. @auto_refresh_token.setter
  153. def auto_refresh_token(self, value):
  154. allowed_methods = {'get', 'post', 'put', 'delete'}
  155. if not isinstance(value, Iterable):
  156. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  157. if not all(method in allowed_methods for method in value):
  158. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  159. self._auto_refresh_token = value
  160. def __fetch_all(self, url, query=None):
  161. '''Wrapper function to paginate GET requests
  162. :param url: The url on which the query is executed
  163. :param query: Existing query parameters (optional)
  164. :return: Combined results of paginated queries
  165. '''
  166. results = []
  167. # initalize query if it was called with None
  168. if not query:
  169. query = {}
  170. page = 0
  171. query['max'] = self.PAGE_SIZE
  172. # fetch until we can
  173. while True:
  174. query['first'] = page*self.PAGE_SIZE
  175. partial_results = raise_error_from_response(
  176. self.raw_get(url, **query),
  177. KeycloakGetError)
  178. if not partial_results:
  179. break
  180. results.extend(partial_results)
  181. page += 1
  182. return results
  183. def import_realm(self, payload):
  184. """
  185. Import a new realm from a RealmRepresentation. Realm name must be unique.
  186. RealmRepresentation
  187. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  188. :param payload: RealmRepresentation
  189. :return: RealmRepresentation
  190. """
  191. data_raw = self.raw_post(URL_ADMIN_REALMS,
  192. data=json.dumps(payload))
  193. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  194. def get_realms(self):
  195. """
  196. Lists all realms in Keycloak deployment
  197. :return: realms list
  198. """
  199. data_raw = self.raw_get(URL_ADMIN_REALMS)
  200. return raise_error_from_response(data_raw, KeycloakGetError)
  201. def create_realm(self, payload, skip_exists=False):
  202. """
  203. Create a realm
  204. RealmRepresentation:
  205. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  206. :param payload: RealmRepresentation
  207. :param skip_exists: Skip if Realm already exist.
  208. :return: Keycloak server response (RealmRepresentation)
  209. """
  210. data_raw = self.raw_post(URL_ADMIN_REALMS,
  211. data=json.dumps(payload))
  212. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  213. def update_realm(self, realm_name, payload):
  214. """
  215. Update a realm. This wil only update top level attributes and will ignore any user,
  216. role, or client information in the payload.
  217. RealmRepresentation:
  218. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  219. :param realm_name: Realm name (not the realm id)
  220. :param payload: RealmRepresentation
  221. :return: Http response
  222. """
  223. params_path = {"realm-name": realm_name}
  224. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  225. data=json.dumps(payload))
  226. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  227. def delete_realm(self, realm_name):
  228. """
  229. Delete a realm
  230. :param realm_name: Realm name (not the realm id)
  231. :return: Http response
  232. """
  233. params_path = {"realm-name": realm_name}
  234. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  235. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  236. def get_users(self, query=None):
  237. """
  238. Return a list of users, filtered according to query parameters
  239. UserRepresentation
  240. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  241. :param query: Query parameters (optional)
  242. :return: users list
  243. """
  244. params_path = {"realm-name": self.realm_name}
  245. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  246. def get_idps(self):
  247. """
  248. Returns a list of ID Providers,
  249. IdentityProviderRepresentation
  250. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  251. :return: array IdentityProviderRepresentation
  252. """
  253. params_path = {"realm-name": self.realm_name}
  254. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  255. return raise_error_from_response(data_raw, KeycloakGetError)
  256. def create_user(self, payload):
  257. """
  258. Create a new user. Username must be unique
  259. UserRepresentation
  260. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  261. :param payload: UserRepresentation
  262. :return: UserRepresentation
  263. """
  264. params_path = {"realm-name": self.realm_name}
  265. exists = self.get_user_id(username=payload['username'])
  266. if exists is not None:
  267. return str(exists)
  268. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  269. data=json.dumps(payload))
  270. raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  271. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  272. return data_raw.headers['Location'][_last_slash_idx + 1:]
  273. def users_count(self):
  274. """
  275. User counter
  276. :return: counter
  277. """
  278. params_path = {"realm-name": self.realm_name}
  279. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  280. return raise_error_from_response(data_raw, KeycloakGetError)
  281. def get_user_id(self, username):
  282. """
  283. Get internal keycloak user id from username
  284. This is required for further actions against this user.
  285. UserRepresentation
  286. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  287. :param username: id in UserRepresentation
  288. :return: user_id
  289. """
  290. users = self.get_users(query={"search": username})
  291. return next((user["id"] for user in users if user["username"] == username), None)
  292. def get_user(self, user_id):
  293. """
  294. Get representation of the user
  295. :param user_id: User id
  296. UserRepresentation
  297. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  298. :return: UserRepresentation
  299. """
  300. params_path = {"realm-name": self.realm_name, "id": user_id}
  301. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  302. return raise_error_from_response(data_raw, KeycloakGetError)
  303. def get_user_groups(self, user_id):
  304. """
  305. Returns a list of groups of which the user is a member
  306. :param user_id: User id
  307. :return: user groups list
  308. """
  309. params_path = {"realm-name": self.realm_name, "id": user_id}
  310. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  311. return raise_error_from_response(data_raw, KeycloakGetError)
  312. def update_user(self, user_id, payload):
  313. """
  314. Update the user
  315. :param user_id: User id
  316. :param payload: UserRepresentation
  317. :return: Http response
  318. """
  319. params_path = {"realm-name": self.realm_name, "id": user_id}
  320. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  321. data=json.dumps(payload))
  322. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  323. def delete_user(self, user_id):
  324. """
  325. Delete the user
  326. :param user_id: User id
  327. :return: Http response
  328. """
  329. params_path = {"realm-name": self.realm_name, "id": user_id}
  330. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  331. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  332. def set_user_password(self, user_id, password, temporary=True):
  333. """
  334. Set up a password for the user. If temporary is True, the user will have to reset
  335. the temporary password next time they log in.
  336. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  337. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  338. :param user_id: User id
  339. :param password: New password
  340. :param temporary: True if password is temporary
  341. :return:
  342. """
  343. payload = {"type": "password", "temporary": temporary, "value": password}
  344. params_path = {"realm-name": self.realm_name, "id": user_id}
  345. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  346. data=json.dumps(payload))
  347. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  348. def consents_user(self, user_id):
  349. """
  350. Get consents granted by the user
  351. :param user_id: User id
  352. :return: consents
  353. """
  354. params_path = {"realm-name": self.realm_name, "id": user_id}
  355. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  356. return raise_error_from_response(data_raw, KeycloakGetError)
  357. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  358. """
  359. Send an update account email to the user. An email contains a
  360. link the user can click to perform a set of required actions.
  361. :param user_id: User id
  362. :param payload: A list of actions for the user to complete
  363. :param client_id: Client id (optional)
  364. :param lifespan: Number of seconds after which the generated token expires (optional)
  365. :param redirect_uri: The redirect uri (optional)
  366. :return:
  367. """
  368. params_path = {"realm-name": self.realm_name, "id": user_id}
  369. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  370. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  371. data=payload, **params_query)
  372. return raise_error_from_response(data_raw, KeycloakGetError)
  373. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  374. """
  375. Send a update account email to the user An email contains a
  376. link the user can click to perform a set of required actions.
  377. :param user_id: User id
  378. :param client_id: Client id (optional)
  379. :param redirect_uri: Redirect uri (optional)
  380. :return:
  381. """
  382. params_path = {"realm-name": self.realm_name, "id": user_id}
  383. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  384. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  385. data={}, **params_query)
  386. return raise_error_from_response(data_raw, KeycloakGetError)
  387. def get_sessions(self, user_id):
  388. """
  389. Get sessions associated with the user
  390. :param user_id: id of user
  391. UserSessionRepresentation
  392. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  393. :return: UserSessionRepresentation
  394. """
  395. params_path = {"realm-name": self.realm_name, "id": user_id}
  396. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  397. return raise_error_from_response(data_raw, KeycloakGetError)
  398. def get_server_info(self):
  399. """
  400. Get themes, social providers, auth providers, and event listeners available on this server
  401. ServerInfoRepresentation
  402. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  403. :return: ServerInfoRepresentation
  404. """
  405. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  406. return raise_error_from_response(data_raw, KeycloakGetError)
  407. def get_groups(self):
  408. """
  409. Returns a list of groups belonging to the realm
  410. GroupRepresentation
  411. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  412. :return: array GroupRepresentation
  413. """
  414. params_path = {"realm-name": self.realm_name}
  415. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  416. def get_group(self, group_id):
  417. """
  418. Get group by id. Returns full group details
  419. GroupRepresentation
  420. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  421. :param group_id: The group id
  422. :return: Keycloak server response (GroupRepresentation)
  423. """
  424. params_path = {"realm-name": self.realm_name, "id": group_id}
  425. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  426. return raise_error_from_response(data_raw, KeycloakGetError)
  427. def get_subgroups(self, group, path):
  428. """
  429. Utility function to iterate through nested group structures
  430. GroupRepresentation
  431. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  432. :param name: group (GroupRepresentation)
  433. :param path: group path (string)
  434. :return: Keycloak server response (GroupRepresentation)
  435. """
  436. for subgroup in group["subGroups"]:
  437. if subgroup['path'] == path:
  438. return subgroup
  439. elif subgroup["subGroups"]:
  440. for subgroup in group["subGroups"]:
  441. result = self.get_subgroups(subgroup, path)
  442. if result:
  443. return result
  444. # went through the tree without hits
  445. return None
  446. def get_group_members(self, group_id, **query):
  447. """
  448. Get members by group id. Returns group members
  449. GroupRepresentation
  450. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  451. :param group_id: The group id
  452. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  453. :return: Keycloak server response (UserRepresentation)
  454. """
  455. params_path = {"realm-name": self.realm_name, "id": group_id}
  456. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  457. def get_group_by_path(self, path, search_in_subgroups=False):
  458. """
  459. Get group id based on name or path.
  460. A straight name or path match with a top-level group will return first.
  461. Subgroups are traversed, the first to match path (or name with path) is returned.
  462. GroupRepresentation
  463. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  464. :param path: group path
  465. :param search_in_subgroups: True if want search in the subgroups
  466. :return: Keycloak server response (GroupRepresentation)
  467. """
  468. groups = self.get_groups()
  469. # TODO: Review this code is necessary
  470. for group in groups:
  471. if group['path'] == path:
  472. return group
  473. elif search_in_subgroups and group["subGroups"]:
  474. for group in group["subGroups"]:
  475. if group['path'] == path:
  476. return group
  477. res = self.get_subgroups(group, path)
  478. if res != None:
  479. return res
  480. return None
  481. def create_group(self, payload, parent=None, skip_exists=False):
  482. """
  483. Creates a group in the Realm
  484. :param payload: GroupRepresentation
  485. :param parent: parent group's id. Required to create a sub-group.
  486. :param skip_exists: If true then do not raise an error if it already exists
  487. GroupRepresentation
  488. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  489. :return: Http response
  490. """
  491. if parent is None:
  492. params_path = {"realm-name": self.realm_name}
  493. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  494. data=json.dumps(payload))
  495. else:
  496. params_path = {"realm-name": self.realm_name, "id": parent, }
  497. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  498. data=json.dumps(payload))
  499. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  500. def update_group(self, group_id, payload):
  501. """
  502. Update group, ignores subgroups.
  503. :param group_id: id of group
  504. :param payload: GroupRepresentation with updated information.
  505. GroupRepresentation
  506. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  507. :return: Http response
  508. """
  509. params_path = {"realm-name": self.realm_name, "id": group_id}
  510. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  511. data=json.dumps(payload))
  512. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  513. def group_set_permissions(self, group_id, enabled=True):
  514. """
  515. Enable/Disable permissions for a group. Cannot delete group if disabled
  516. :param group_id: id of group
  517. :param enabled: boolean
  518. :return: Keycloak server response
  519. """
  520. params_path = {"realm-name": self.realm_name, "id": group_id}
  521. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  522. data=json.dumps({"enabled": enabled}))
  523. return raise_error_from_response(data_raw, KeycloakGetError)
  524. def group_user_add(self, user_id, group_id):
  525. """
  526. Add user to group (user_id and group_id)
  527. :param user_id: id of user
  528. :param group_id: id of group to add to
  529. :return: Keycloak server response
  530. """
  531. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  532. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  533. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  534. def group_user_remove(self, user_id, group_id):
  535. """
  536. Remove user from group (user_id and group_id)
  537. :param user_id: id of user
  538. :param group_id: id of group to remove from
  539. :return: Keycloak server response
  540. """
  541. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  542. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  543. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  544. def delete_group(self, group_id):
  545. """
  546. Deletes a group in the Realm
  547. :param group_id: id of group to delete
  548. :return: Keycloak server response
  549. """
  550. params_path = {"realm-name": self.realm_name, "id": group_id}
  551. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  552. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  553. def get_clients(self):
  554. """
  555. Returns a list of clients belonging to the realm
  556. ClientRepresentation
  557. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  558. :return: Keycloak server response (ClientRepresentation)
  559. """
  560. params_path = {"realm-name": self.realm_name}
  561. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  562. return raise_error_from_response(data_raw, KeycloakGetError)
  563. def get_client(self, client_id):
  564. """
  565. Get representation of the client
  566. ClientRepresentation
  567. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  568. :param client_id: id of client (not client-id)
  569. :return: Keycloak server response (ClientRepresentation)
  570. """
  571. params_path = {"realm-name": self.realm_name, "id": client_id}
  572. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  573. return raise_error_from_response(data_raw, KeycloakGetError)
  574. def get_client_id(self, client_name):
  575. """
  576. Get internal keycloak client id from client-id.
  577. This is required for further actions against this client.
  578. :param client_name: name in ClientRepresentation
  579. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  580. :return: client_id (uuid as string)
  581. """
  582. clients = self.get_clients()
  583. for client in clients:
  584. if client_name == client.get('name') or client_name == client.get('clientId'):
  585. return client["id"]
  586. return None
  587. def get_client_authz_settings(self, client_id):
  588. """
  589. Get authorization json from client.
  590. :param client_id: id in ClientRepresentation
  591. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  592. :return: Keycloak server response
  593. """
  594. params_path = {"realm-name": self.realm_name, "id": client_id}
  595. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  596. return data_raw
  597. def get_client_authz_resources(self, client_id):
  598. """
  599. Get resources from client.
  600. :param client_id: id in ClientRepresentation
  601. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  602. :return: Keycloak server response
  603. """
  604. params_path = {"realm-name": self.realm_name, "id": client_id}
  605. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  606. return data_raw
  607. def create_client(self, payload, skip_exists=False):
  608. """
  609. Create a client
  610. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  611. :param skip_exists: If true then do not raise an error if client already exists
  612. :param payload: ClientRepresentation
  613. :return: Keycloak server response (UserRepresentation)
  614. """
  615. params_path = {"realm-name": self.realm_name}
  616. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  617. data=json.dumps(payload))
  618. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  619. def update_client(self, client_id, payload):
  620. """
  621. Update a client
  622. :param client_id: Client id
  623. :param payload: ClientRepresentation
  624. :return: Http response
  625. """
  626. params_path = {"realm-name": self.realm_name, "id": client_id}
  627. data_raw = self.connection.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  628. data=json.dumps(payload))
  629. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  630. def delete_client(self, client_id):
  631. """
  632. Get representation of the client
  633. ClientRepresentation
  634. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  635. :param client_id: keycloak client id (not oauth client-id)
  636. :return: Keycloak server response (ClientRepresentation)
  637. """
  638. params_path = {"realm-name": self.realm_name, "id": client_id}
  639. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  640. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  641. def get_realm_roles(self):
  642. """
  643. Get all roles for the realm or client
  644. RoleRepresentation
  645. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  646. :return: Keycloak server response (RoleRepresentation)
  647. """
  648. params_path = {"realm-name": self.realm_name}
  649. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  650. return raise_error_from_response(data_raw, KeycloakGetError)
  651. def get_client_roles(self, client_id):
  652. """
  653. Get all roles for the client
  654. :param client_id: id of client (not client-id)
  655. RoleRepresentation
  656. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  657. :return: Keycloak server response (RoleRepresentation)
  658. """
  659. params_path = {"realm-name": self.realm_name, "id": client_id}
  660. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  661. return raise_error_from_response(data_raw, KeycloakGetError)
  662. def get_client_role(self, client_id, role_name):
  663. """
  664. Get client role id by name
  665. This is required for further actions with this role.
  666. :param client_id: id of client (not client-id)
  667. :param role_name: roles name (not id!)
  668. RoleRepresentation
  669. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  670. :return: role_id
  671. """
  672. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  673. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  674. return raise_error_from_response(data_raw, KeycloakGetError)
  675. def get_client_role_id(self, client_id, role_name):
  676. """
  677. Warning: Deprecated
  678. Get client role id by name
  679. This is required for further actions with this role.
  680. :param client_id: id of client (not client-id)
  681. :param role_name: roles name (not id!)
  682. RoleRepresentation
  683. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  684. :return: role_id
  685. """
  686. role = self.get_client_role(client_id, role_name)
  687. return role.get("id")
  688. def create_client_role(self, client_role_id, payload, skip_exists=False):
  689. """
  690. Create a client role
  691. RoleRepresentation
  692. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  693. :param client_role_id: id of client (not client-id)
  694. :param payload: RoleRepresentation
  695. :param skip_exists: If true then do not raise an error if client role already exists
  696. :return: Keycloak server response (RoleRepresentation)
  697. """
  698. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  699. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  700. data=json.dumps(payload))
  701. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  702. def delete_client_role(self, client_role_id, role_name):
  703. """
  704. Delete a client role
  705. RoleRepresentation
  706. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  707. :param client_role_id: id of client (not client-id)
  708. :param role_name: roles name (not id!)
  709. """
  710. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  711. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  712. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  713. def assign_client_role(self, user_id, client_id, roles):
  714. """
  715. Assign a client role to a user
  716. :param user_id: id of user
  717. :param client_id: id of client (not client-id)
  718. :param roles: roles list or role (use RoleRepresentation)
  719. :return Keycloak server response
  720. """
  721. payload = roles if isinstance(roles, list) else [roles]
  722. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  723. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  724. data=json.dumps(payload))
  725. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  726. def create_realm_role(self, payload, skip_exists=False):
  727. """
  728. Create a new role for the realm or client
  729. :param payload: The role (use RoleRepresentation)
  730. :param skip_exists: If true then do not raise an error if realm role already exists
  731. :return Keycloak server response
  732. """
  733. params_path = {"realm-name": self.realm_name}
  734. data_raw = self.connection.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  735. data=json.dumps(payload))
  736. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  737. def assign_realm_roles(self, user_id, client_id, roles):
  738. """
  739. Assign realm roles to a user
  740. :param user_id: id of user
  741. :param client_id: id of client containing role (not client-id)
  742. :param roles: roles list or role (use RoleRepresentation)
  743. :return Keycloak server response
  744. """
  745. payload = roles if isinstance(roles, list) else [roles]
  746. params_path = {"realm-name": self.realm_name, "id": user_id}
  747. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  748. data=json.dumps(payload))
  749. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  750. def assign_group_realm_roles(self, group_id, roles):
  751. """
  752. Assign realm roles to a group
  753. :param group_id: id of groupp
  754. :param roles: roles list or role (use GroupRoleRepresentation)
  755. :return Keycloak server response
  756. """
  757. payload = roles if isinstance(roles, list) else [roles]
  758. params_path = {"realm-name": self.realm_name, "id": group_id}
  759. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  760. data=json.dumps(payload))
  761. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  762. def delete_group_realm_roles(self, group_id, roles):
  763. """
  764. Delete realm roles of a group
  765. :param group_id: id of group
  766. :param roles: roles list or role (use GroupRoleRepresentation)
  767. :return Keycloak server response
  768. """
  769. payload = roles if isinstance(roles, list) else [roles]
  770. params_path = {"realm-name": self.realm_name, "id": group_id}
  771. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  772. data=json.dumps(payload))
  773. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  774. def get_group_realm_roles(self, group_id):
  775. """
  776. Get all realm roles for a group.
  777. :param user_id: id of the group
  778. :return: Keycloak server response (array RoleRepresentation)
  779. """
  780. params_path = {"realm-name": self.realm_name, "id": group_id}
  781. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  782. return raise_error_from_response(data_raw, KeycloakGetError)
  783. def get_client_roles_of_user(self, user_id, client_id):
  784. """
  785. Get all client roles for a user.
  786. :param user_id: id of user
  787. :param client_id: id of client (not client-id)
  788. :return: Keycloak server response (array RoleRepresentation)
  789. """
  790. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  791. def get_available_client_roles_of_user(self, user_id, client_id):
  792. """
  793. Get available client role-mappings for a user.
  794. :param user_id: id of user
  795. :param client_id: id of client (not client-id)
  796. :return: Keycloak server response (array RoleRepresentation)
  797. """
  798. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  799. def get_composite_client_roles_of_user(self, user_id, client_id):
  800. """
  801. Get composite client role-mappings for a user.
  802. :param user_id: id of user
  803. :param client_id: id of client (not client-id)
  804. :return: Keycloak server response (array RoleRepresentation)
  805. """
  806. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  807. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  808. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  809. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  810. return raise_error_from_response(data_raw, KeycloakGetError)
  811. def delete_client_roles_of_user(self, user_id, client_id, roles):
  812. """
  813. Delete client roles from a user.
  814. :param user_id: id of user
  815. :param client_id: id of client containing role (not client-id)
  816. :param roles: roles list or role to delete (use RoleRepresentation)
  817. :return: Keycloak server response
  818. """
  819. payload = roles if isinstance(roles, list) else [roles]
  820. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  821. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  822. data=json.dumps(payload))
  823. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  824. def get_authentication_flows(self):
  825. """
  826. Get authentication flows. Returns all flow details
  827. AuthenticationFlowRepresentation
  828. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  829. :return: Keycloak server response (AuthenticationFlowRepresentation)
  830. """
  831. params_path = {"realm-name": self.realm_name}
  832. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  833. return raise_error_from_response(data_raw, KeycloakGetError)
  834. def create_authentication_flow(self, payload, skip_exists=False):
  835. """
  836. Create a new authentication flow
  837. AuthenticationFlowRepresentation
  838. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  839. :param payload: AuthenticationFlowRepresentation
  840. :param skip_exists: If true then do not raise an error if authentication flow already exists
  841. :return: Keycloak server response (RoleRepresentation)
  842. """
  843. params_path = {"realm-name": self.realm_name}
  844. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  845. data=payload)
  846. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  847. def get_authentication_flow_executions(self, flow_alias):
  848. """
  849. Get authentication flow executions. Returns all execution steps
  850. :param flow_alias: the flow alias
  851. :return: Response(json)
  852. """
  853. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  854. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  855. return raise_error_from_response(data_raw, KeycloakGetError)
  856. def update_authentication_flow_executions(self, payload, flow_alias):
  857. """
  858. Update an authentication flow execution
  859. AuthenticationExecutionInfoRepresentation
  860. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  861. :param payload: AuthenticationExecutionInfoRepresentation
  862. :param flow_alias: The flow alias
  863. :return: Keycloak server response
  864. """
  865. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  866. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  867. data=payload)
  868. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  869. def sync_users(self, storage_id, action):
  870. """
  871. Function to trigger user sync from provider
  872. :param storage_id: The id of the user storage provider
  873. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  874. :return:
  875. """
  876. data = {'action': action}
  877. params_query = {"action": action}
  878. params_path = {"realm-name": self.realm_name, "id": storage_id}
  879. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  880. data=json.dumps(data), **params_query)
  881. return raise_error_from_response(data_raw, KeycloakGetError)
  882. def get_client_scopes(self):
  883. """
  884. Get representation of the client scopes for the realm where we are connected to
  885. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  886. :return: Keycloak server response Array of (ClientScopeRepresentation)
  887. """
  888. params_path = {"realm-name": self.realm_name}
  889. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  890. return raise_error_from_response(data_raw, KeycloakGetError)
  891. def get_client_scope(self, client_scope_id):
  892. """
  893. Get representation of the client scopes for the realm where we are connected to
  894. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  895. :param client_scope_id: The id of the client scope
  896. :return: Keycloak server response (ClientScopeRepresentation)
  897. """
  898. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  899. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  900. return raise_error_from_response(data_raw, KeycloakGetError)
  901. def add_mapper_to_client_scope(self, client_scope_id, payload):
  902. """
  903. Add a mapper to a client scope
  904. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  905. :param client_scope_id: The id of the client scope
  906. :param payload: ProtocolMapperRepresentation
  907. :return: Keycloak server Response
  908. """
  909. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  910. data_raw = self.raw_post(
  911. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  912. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  913. def generate_client_secrets(self, client_id):
  914. """
  915. Generate a new secret for the client
  916. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  917. :param client_id: id of client (not client-id)
  918. :return: Keycloak server response (ClientRepresentation)
  919. """
  920. params_path = {"realm-name": self.realm_name, "id": client_id}
  921. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  922. return raise_error_from_response(data_raw, KeycloakGetError)
  923. def get_client_secrets(self, client_id):
  924. """
  925. Get representation of the client secrets
  926. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  927. :param client_id: id of client (not client-id)
  928. :return: Keycloak server response (ClientRepresentation)
  929. """
  930. params_path = {"realm-name": self.realm_name, "id": client_id}
  931. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  932. return raise_error_from_response(data_raw, KeycloakGetError)
  933. def raw_get(self, *args, **kwargs):
  934. """
  935. Calls connection.raw_get.
  936. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  937. and try *get* once more.
  938. """
  939. r = self.connection.raw_get(*args, **kwargs)
  940. if 'get' in self.auto_refresh_token and r.status_code == 401:
  941. self.refresh_token()
  942. return self.connection.raw_get(*args, **kwargs)
  943. return r
  944. def raw_post(self, *args, **kwargs):
  945. """
  946. Calls connection.raw_post.
  947. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  948. and try *post* once more.
  949. """
  950. r = self.connection.raw_post(*args, **kwargs)
  951. if 'post' in self.auto_refresh_token and r.status_code == 401:
  952. self.refresh_token()
  953. return self.connection.raw_post(*args, **kwargs)
  954. return r
  955. def raw_put(self, *args, **kwargs):
  956. """
  957. Calls connection.raw_put.
  958. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  959. and try *put* once more.
  960. """
  961. r = self.connection.raw_put(*args, **kwargs)
  962. if 'put' in self.auto_refresh_token and r.status_code == 401:
  963. self.refresh_token()
  964. return self.connection.raw_put(*args, **kwargs)
  965. return r
  966. def raw_delete(self, *args, **kwargs):
  967. """
  968. Calls connection.raw_delete.
  969. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  970. and try *delete* once more.
  971. """
  972. r = self.connection.raw_delete(*args, **kwargs)
  973. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  974. self.refresh_token()
  975. return self.connection.raw_delete(*args, **kwargs)
  976. return r
  977. def get_token(self):
  978. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  979. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  980. client_secret_key=self.client_secret_key,
  981. custom_headers=self.custom_headers)
  982. grant_type = ["password"]
  983. if self.client_secret_key:
  984. grant_type = ["client_credentials"]
  985. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  986. headers = {
  987. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  988. 'Content-Type': 'application/json'
  989. }
  990. if self.custom_headers is not None:
  991. # merge custom headers to main headers
  992. headers.update(self.custom_headers)
  993. self._connection = ConnectionManager(base_url=self.server_url,
  994. headers=headers,
  995. timeout=60,
  996. verify=self.verify)
  997. def refresh_token(self):
  998. refresh_token = self.token.get('refresh_token')
  999. try:
  1000. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1001. except KeycloakGetError as e:
  1002. if e.response_code == 400 and b'Refresh token expired' in e.response_body:
  1003. self.get_token()
  1004. else:
  1005. raise
  1006. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))