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.

1829 lines
72 KiB

7 years ago
6 years ago
6 years ago
4 years ago
6 years ago
7 years ago
6 years ago
4 years ago
4 years ago
4 years ago
6 years ago
6 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
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
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
4 years ago
6 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 Iterable
  28. from .connection import ConnectionManager
  29. from .exceptions import raise_error_from_response, KeycloakGetError
  30. from .keycloak_openid import KeycloakOpenID
  31. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  32. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_GROUPS_REALM_ROLES, \
  33. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE, URL_ADMIN_CLIENT_INSTALLATION_PROVIDER, \
  34. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GET_GROUPS_REALM_ROLES, URL_ADMIN_GROUPS_CLIENT_ROLES, \
  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, URL_ADMIN_IDP, \
  40. URL_ADMIN_IDP_MAPPERS, 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, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS, \
  43. URL_ADMIN_USER_FEDERATED_IDENTITY, URL_ADMIN_USER_FEDERATED_IDENTITIES, URL_ADMIN_CLIENT_ROLE_MEMBERS, \
  44. URL_ADMIN_REALM_ROLES_MEMBERS, URL_ADMIN_CLIENT_PROTOCOL_MAPPER, URL_ADMIN_CLIENT_SCOPES_MAPPERS, \
  45. URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION, URL_ADMIN_FLOWS_EXECUTIONS_FLOW, URL_ADMIN_FLOWS_COPY, \
  46. URL_ADMIN_FLOWS_ALIAS, URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER, URL_ADMIN_AUTHENTICATOR_CONFIG, \
  47. URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE
  48. class KeycloakAdmin:
  49. PAGE_SIZE = 100
  50. _server_url = None
  51. _username = None
  52. _password = None
  53. _realm_name = None
  54. _client_id = None
  55. _verify = None
  56. _client_secret_key = None
  57. _auto_refresh_token = None
  58. _connection = None
  59. _token = None
  60. _custom_headers = None
  61. _user_realm_name = None
  62. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  63. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  64. """
  65. :param server_url: Keycloak server url
  66. :param username: admin username
  67. :param password: admin password
  68. :param realm_name: realm name
  69. :param client_id: client id
  70. :param verify: True if want check connection SSL
  71. :param client_secret_key: client secret key
  72. :param custom_headers: dict of custom header to pass to each HTML request
  73. :param user_realm_name: The realm name of the user, if different from realm_name
  74. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  75. """
  76. self.server_url = server_url
  77. self.username = username
  78. self.password = password
  79. self.realm_name = realm_name
  80. self.client_id = client_id
  81. self.verify = verify
  82. self.client_secret_key = client_secret_key
  83. self.auto_refresh_token = auto_refresh_token or []
  84. self.user_realm_name = user_realm_name
  85. self.custom_headers = custom_headers
  86. # Get token Admin
  87. self.get_token()
  88. @property
  89. def server_url(self):
  90. return self._server_url
  91. @server_url.setter
  92. def server_url(self, value):
  93. self._server_url = value
  94. @property
  95. def realm_name(self):
  96. return self._realm_name
  97. @realm_name.setter
  98. def realm_name(self, value):
  99. self._realm_name = value
  100. @property
  101. def connection(self):
  102. return self._connection
  103. @connection.setter
  104. def connection(self, value):
  105. self._connection = value
  106. @property
  107. def client_id(self):
  108. return self._client_id
  109. @client_id.setter
  110. def client_id(self, value):
  111. self._client_id = value
  112. @property
  113. def client_secret_key(self):
  114. return self._client_secret_key
  115. @client_secret_key.setter
  116. def client_secret_key(self, value):
  117. self._client_secret_key = value
  118. @property
  119. def verify(self):
  120. return self._verify
  121. @verify.setter
  122. def verify(self, value):
  123. self._verify = value
  124. @property
  125. def username(self):
  126. return self._username
  127. @username.setter
  128. def username(self, value):
  129. self._username = value
  130. @property
  131. def password(self):
  132. return self._password
  133. @password.setter
  134. def password(self, value):
  135. self._password = value
  136. @property
  137. def token(self):
  138. return self._token
  139. @token.setter
  140. def token(self, value):
  141. self._token = value
  142. @property
  143. def auto_refresh_token(self):
  144. return self._auto_refresh_token
  145. @property
  146. def user_realm_name(self):
  147. return self._user_realm_name
  148. @user_realm_name.setter
  149. def user_realm_name(self, value):
  150. self._user_realm_name = value
  151. @property
  152. def custom_headers(self):
  153. return self._custom_headers
  154. @custom_headers.setter
  155. def custom_headers(self, value):
  156. self._custom_headers = value
  157. @auto_refresh_token.setter
  158. def auto_refresh_token(self, value):
  159. allowed_methods = {'get', 'post', 'put', 'delete'}
  160. if not isinstance(value, Iterable):
  161. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  162. if not all(method in allowed_methods for method in value):
  163. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  164. self._auto_refresh_token = value
  165. def __fetch_all(self, url, query=None):
  166. '''Wrapper function to paginate GET requests
  167. :param url: The url on which the query is executed
  168. :param query: Existing query parameters (optional)
  169. :return: Combined results of paginated queries
  170. '''
  171. results = []
  172. # initalize query if it was called with None
  173. if not query:
  174. query = {}
  175. page = 0
  176. query['max'] = self.PAGE_SIZE
  177. # fetch until we can
  178. while True:
  179. query['first'] = page*self.PAGE_SIZE
  180. partial_results = raise_error_from_response(
  181. self.raw_get(url, **query),
  182. KeycloakGetError)
  183. if not partial_results:
  184. break
  185. results.extend(partial_results)
  186. page += 1
  187. return results
  188. def import_realm(self, payload):
  189. """
  190. Import a new realm from a RealmRepresentation. Realm name must be unique.
  191. RealmRepresentation
  192. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  193. :param payload: RealmRepresentation
  194. :return: RealmRepresentation
  195. """
  196. data_raw = self.raw_post(URL_ADMIN_REALMS,
  197. data=json.dumps(payload))
  198. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  199. def get_realms(self):
  200. """
  201. Lists all realms in Keycloak deployment
  202. :return: realms list
  203. """
  204. data_raw = self.raw_get(URL_ADMIN_REALMS)
  205. return raise_error_from_response(data_raw, KeycloakGetError)
  206. def create_realm(self, payload, skip_exists=False):
  207. """
  208. Create a realm
  209. RealmRepresentation:
  210. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  211. :param payload: RealmRepresentation
  212. :param skip_exists: Skip if Realm already exist.
  213. :return: Keycloak server response (RealmRepresentation)
  214. """
  215. data_raw = self.raw_post(URL_ADMIN_REALMS,
  216. data=json.dumps(payload))
  217. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  218. def update_realm(self, realm_name, payload):
  219. """
  220. Update a realm. This wil only update top level attributes and will ignore any user,
  221. role, or client information in the payload.
  222. RealmRepresentation:
  223. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  224. :param realm_name: Realm name (not the realm id)
  225. :param payload: RealmRepresentation
  226. :return: Http response
  227. """
  228. params_path = {"realm-name": realm_name}
  229. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  230. data=json.dumps(payload))
  231. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  232. def delete_realm(self, realm_name):
  233. """
  234. Delete a realm
  235. :param realm_name: Realm name (not the realm id)
  236. :return: Http response
  237. """
  238. params_path = {"realm-name": realm_name}
  239. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  240. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  241. def get_users(self, query=None):
  242. """
  243. Return a list of users, filtered according to query parameters
  244. UserRepresentation
  245. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  246. :param query: Query parameters (optional)
  247. :return: users list
  248. """
  249. params_path = {"realm-name": self.realm_name}
  250. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  251. def create_idp(self, payload):
  252. """
  253. Create an ID Provider,
  254. IdentityProviderRepresentation
  255. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  256. :param: payload: IdentityProviderRepresentation
  257. """
  258. params_path = {"realm-name": self.realm_name}
  259. data_raw = self.raw_post(URL_ADMIN_IDPS.format(**params_path),
  260. data=json.dumps(payload))
  261. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  262. def add_mapper_to_idp(self, idp_alias, payload):
  263. """
  264. Create an ID Provider,
  265. IdentityProviderRepresentation
  266. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityprovidermapperrepresentation
  267. :param: idp_alias: alias for Idp to add mapper in
  268. :param: payload: IdentityProviderMapperRepresentation
  269. """
  270. params_path = {"realm-name": self.realm_name, "idp-alias": idp_alias}
  271. data_raw = self.raw_post(URL_ADMIN_IDP_MAPPERS.format(**params_path),
  272. data=json.dumps(payload))
  273. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  274. def get_idps(self):
  275. """
  276. Returns a list of ID Providers,
  277. IdentityProviderRepresentation
  278. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  279. :return: array IdentityProviderRepresentation
  280. """
  281. params_path = {"realm-name": self.realm_name}
  282. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  283. return raise_error_from_response(data_raw, KeycloakGetError)
  284. def delete_idp(self, idp_alias):
  285. """
  286. Deletes ID Provider,
  287. :param: idp_alias: idp alias name
  288. """
  289. params_path = {"realm-name": self.realm_name, "alias": idp_alias}
  290. data_raw = self.raw_delete(URL_ADMIN_IDP.format(**params_path))
  291. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  292. def create_user(self, payload):
  293. """
  294. Create a new user. Username must be unique
  295. UserRepresentation
  296. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  297. :param payload: UserRepresentation
  298. :return: UserRepresentation
  299. """
  300. params_path = {"realm-name": self.realm_name}
  301. exists = self.get_user_id(username=payload['username'])
  302. if exists is not None:
  303. return str(exists)
  304. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  305. data=json.dumps(payload))
  306. raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  307. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  308. return data_raw.headers['Location'][_last_slash_idx + 1:]
  309. def users_count(self):
  310. """
  311. User counter
  312. :return: counter
  313. """
  314. params_path = {"realm-name": self.realm_name}
  315. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  316. return raise_error_from_response(data_raw, KeycloakGetError)
  317. def get_user_id(self, username):
  318. """
  319. Get internal keycloak user id from username
  320. This is required for further actions against this user.
  321. UserRepresentation
  322. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  323. :param username: id in UserRepresentation
  324. :return: user_id
  325. """
  326. users = self.get_users(query={"search": username})
  327. return next((user["id"] for user in users if user["username"] == username), None)
  328. def get_user(self, user_id):
  329. """
  330. Get representation of the user
  331. :param user_id: User id
  332. UserRepresentation
  333. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  334. :return: UserRepresentation
  335. """
  336. params_path = {"realm-name": self.realm_name, "id": user_id}
  337. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  338. return raise_error_from_response(data_raw, KeycloakGetError)
  339. def get_user_groups(self, user_id):
  340. """
  341. Returns a list of groups of which the user is a member
  342. :param user_id: User id
  343. :return: user groups list
  344. """
  345. params_path = {"realm-name": self.realm_name, "id": user_id}
  346. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  347. return raise_error_from_response(data_raw, KeycloakGetError)
  348. def update_user(self, user_id, payload):
  349. """
  350. Update the user
  351. :param user_id: User id
  352. :param payload: UserRepresentation
  353. :return: Http response
  354. """
  355. params_path = {"realm-name": self.realm_name, "id": user_id}
  356. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  357. data=json.dumps(payload))
  358. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  359. def delete_user(self, user_id):
  360. """
  361. Delete the user
  362. :param user_id: User id
  363. :return: Http response
  364. """
  365. params_path = {"realm-name": self.realm_name, "id": user_id}
  366. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  367. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  368. def set_user_password(self, user_id, password, temporary=True):
  369. """
  370. Set up a password for the user. If temporary is True, the user will have to reset
  371. the temporary password next time they log in.
  372. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  373. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  374. :param user_id: User id
  375. :param password: New password
  376. :param temporary: True if password is temporary
  377. :return:
  378. """
  379. payload = {"type": "password", "temporary": temporary, "value": password}
  380. params_path = {"realm-name": self.realm_name, "id": user_id}
  381. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  382. data=json.dumps(payload))
  383. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  384. def consents_user(self, user_id):
  385. """
  386. Get consents granted by the user
  387. :param user_id: User id
  388. :return: consents
  389. """
  390. params_path = {"realm-name": self.realm_name, "id": user_id}
  391. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  392. return raise_error_from_response(data_raw, KeycloakGetError)
  393. def get_user_social_logins(self, user_id):
  394. """
  395. Returns a list of federated identities/social logins of which the user has been associated with
  396. :param user_id: User id
  397. :return: federated identities list
  398. """
  399. params_path = {"realm-name": self.realm_name, "id": user_id}
  400. data_raw = self.raw_get(URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path))
  401. return raise_error_from_response(data_raw, KeycloakGetError)
  402. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  403. """
  404. Add a federated identity / social login provider to the user
  405. :param user_id: User id
  406. :param provider_id: Social login provider id
  407. :param provider_userid: userid specified by the provider
  408. :param provider_username: username specified by the provider
  409. :return:
  410. """
  411. payload = {"identityProvider": provider_id, "userId": provider_userid, "userName": provider_username}
  412. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  413. data_raw = self.raw_post(URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path), data=json.dumps(payload))
  414. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  415. """
  416. Send an update account email to the user. An email contains a
  417. link the user can click to perform a set of required actions.
  418. :param user_id: User id
  419. :param payload: A list of actions for the user to complete
  420. :param client_id: Client id (optional)
  421. :param lifespan: Number of seconds after which the generated token expires (optional)
  422. :param redirect_uri: The redirect uri (optional)
  423. :return:
  424. """
  425. params_path = {"realm-name": self.realm_name, "id": user_id}
  426. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  427. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  428. data=payload, **params_query)
  429. return raise_error_from_response(data_raw, KeycloakGetError)
  430. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  431. """
  432. Send a update account email to the user An email contains a
  433. link the user can click to perform a set of required actions.
  434. :param user_id: User id
  435. :param client_id: Client id (optional)
  436. :param redirect_uri: Redirect uri (optional)
  437. :return:
  438. """
  439. params_path = {"realm-name": self.realm_name, "id": user_id}
  440. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  441. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  442. data={}, **params_query)
  443. return raise_error_from_response(data_raw, KeycloakGetError)
  444. def get_sessions(self, user_id):
  445. """
  446. Get sessions associated with the user
  447. :param user_id: id of user
  448. UserSessionRepresentation
  449. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  450. :return: UserSessionRepresentation
  451. """
  452. params_path = {"realm-name": self.realm_name, "id": user_id}
  453. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  454. return raise_error_from_response(data_raw, KeycloakGetError)
  455. def get_server_info(self):
  456. """
  457. Get themes, social providers, auth providers, and event listeners available on this server
  458. ServerInfoRepresentation
  459. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  460. :return: ServerInfoRepresentation
  461. """
  462. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  463. return raise_error_from_response(data_raw, KeycloakGetError)
  464. def get_groups(self):
  465. """
  466. Returns a list of groups belonging to the realm
  467. GroupRepresentation
  468. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  469. :return: array GroupRepresentation
  470. """
  471. params_path = {"realm-name": self.realm_name}
  472. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  473. def get_group(self, group_id):
  474. """
  475. Get group by id. Returns full group details
  476. GroupRepresentation
  477. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  478. :param group_id: The group id
  479. :return: Keycloak server response (GroupRepresentation)
  480. """
  481. params_path = {"realm-name": self.realm_name, "id": group_id}
  482. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  483. return raise_error_from_response(data_raw, KeycloakGetError)
  484. def get_subgroups(self, group, path):
  485. """
  486. Utility function to iterate through nested group structures
  487. GroupRepresentation
  488. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  489. :param name: group (GroupRepresentation)
  490. :param path: group path (string)
  491. :return: Keycloak server response (GroupRepresentation)
  492. """
  493. for subgroup in group["subGroups"]:
  494. if subgroup['path'] == path:
  495. return subgroup
  496. elif subgroup["subGroups"]:
  497. for subgroup in group["subGroups"]:
  498. result = self.get_subgroups(subgroup, path)
  499. if result:
  500. return result
  501. # went through the tree without hits
  502. return None
  503. def get_group_members(self, group_id, **query):
  504. """
  505. Get members by group id. Returns group members
  506. GroupRepresentation
  507. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  508. :param group_id: The group id
  509. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  510. :return: Keycloak server response (UserRepresentation)
  511. """
  512. params_path = {"realm-name": self.realm_name, "id": group_id}
  513. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  514. def get_group_by_path(self, path, search_in_subgroups=False):
  515. """
  516. Get group id based on name or path.
  517. A straight name or path match with a top-level group will return first.
  518. Subgroups are traversed, the first to match path (or name with path) is returned.
  519. GroupRepresentation
  520. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  521. :param path: group path
  522. :param search_in_subgroups: True if want search in the subgroups
  523. :return: Keycloak server response (GroupRepresentation)
  524. """
  525. groups = self.get_groups()
  526. # TODO: Review this code is necessary
  527. for group in groups:
  528. if group['path'] == path:
  529. return group
  530. elif search_in_subgroups and group["subGroups"]:
  531. for group in group["subGroups"]:
  532. if group['path'] == path:
  533. return group
  534. res = self.get_subgroups(group, path)
  535. if res != None:
  536. return res
  537. return None
  538. def create_group(self, payload, parent=None, skip_exists=False):
  539. """
  540. Creates a group in the Realm
  541. :param payload: GroupRepresentation
  542. :param parent: parent group's id. Required to create a sub-group.
  543. :param skip_exists: If true then do not raise an error if it already exists
  544. GroupRepresentation
  545. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  546. :return: Http response
  547. """
  548. if parent is None:
  549. params_path = {"realm-name": self.realm_name}
  550. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  551. data=json.dumps(payload))
  552. else:
  553. params_path = {"realm-name": self.realm_name, "id": parent, }
  554. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  555. data=json.dumps(payload))
  556. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  557. def update_group(self, group_id, payload):
  558. """
  559. Update group, ignores subgroups.
  560. :param group_id: id of group
  561. :param payload: GroupRepresentation with updated information.
  562. GroupRepresentation
  563. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  564. :return: Http response
  565. """
  566. params_path = {"realm-name": self.realm_name, "id": group_id}
  567. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  568. data=json.dumps(payload))
  569. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  570. def group_set_permissions(self, group_id, enabled=True):
  571. """
  572. Enable/Disable permissions for a group. Cannot delete group if disabled
  573. :param group_id: id of group
  574. :param enabled: boolean
  575. :return: Keycloak server response
  576. """
  577. params_path = {"realm-name": self.realm_name, "id": group_id}
  578. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  579. data=json.dumps({"enabled": enabled}))
  580. return raise_error_from_response(data_raw, KeycloakGetError)
  581. def group_user_add(self, user_id, group_id):
  582. """
  583. Add user to group (user_id and group_id)
  584. :param user_id: id of user
  585. :param group_id: id of group to add to
  586. :return: Keycloak server response
  587. """
  588. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  589. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  590. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  591. def group_user_remove(self, user_id, group_id):
  592. """
  593. Remove user from group (user_id and group_id)
  594. :param user_id: id of user
  595. :param group_id: id of group to remove from
  596. :return: Keycloak server response
  597. """
  598. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  599. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  600. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  601. def delete_group(self, group_id):
  602. """
  603. Deletes a group in the Realm
  604. :param group_id: id of group to delete
  605. :return: Keycloak server response
  606. """
  607. params_path = {"realm-name": self.realm_name, "id": group_id}
  608. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  609. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  610. def get_clients(self):
  611. """
  612. Returns a list of clients belonging to the realm
  613. ClientRepresentation
  614. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  615. :return: Keycloak server response (ClientRepresentation)
  616. """
  617. params_path = {"realm-name": self.realm_name}
  618. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  619. return raise_error_from_response(data_raw, KeycloakGetError)
  620. def get_client(self, client_id):
  621. """
  622. Get representation of the client
  623. ClientRepresentation
  624. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  625. :param client_id: id of client (not client-id)
  626. :return: Keycloak server response (ClientRepresentation)
  627. """
  628. params_path = {"realm-name": self.realm_name, "id": client_id}
  629. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  630. return raise_error_from_response(data_raw, KeycloakGetError)
  631. def get_client_id(self, client_name):
  632. """
  633. Get internal keycloak client id from client-id.
  634. This is required for further actions against this client.
  635. :param client_name: name in ClientRepresentation
  636. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  637. :return: client_id (uuid as string)
  638. """
  639. clients = self.get_clients()
  640. for client in clients:
  641. if client_name == client.get('name') or client_name == client.get('clientId'):
  642. return client["id"]
  643. return None
  644. def get_client_authz_settings(self, client_id):
  645. """
  646. Get authorization json from client.
  647. :param client_id: id in ClientRepresentation
  648. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  649. :return: Keycloak server response
  650. """
  651. params_path = {"realm-name": self.realm_name, "id": client_id}
  652. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  653. return data_raw
  654. def get_client_authz_resources(self, client_id):
  655. """
  656. Get resources from client.
  657. :param client_id: id in ClientRepresentation
  658. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  659. :return: Keycloak server response
  660. """
  661. params_path = {"realm-name": self.realm_name, "id": client_id}
  662. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  663. return data_raw
  664. def get_client_service_account_user(self, client_id):
  665. """
  666. Get service account user from client.
  667. :param client_id: id in ClientRepresentation
  668. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  669. :return: UserRepresentation
  670. """
  671. params_path = {"realm-name": self.realm_name, "id": client_id}
  672. data_raw = self.raw_get(URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path))
  673. return raise_error_from_response(data_raw, KeycloakGetError)
  674. def create_client(self, payload, skip_exists=False):
  675. """
  676. Create a client
  677. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  678. :param skip_exists: If true then do not raise an error if client already exists
  679. :param payload: ClientRepresentation
  680. :return: Keycloak server response (UserRepresentation)
  681. """
  682. params_path = {"realm-name": self.realm_name}
  683. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  684. data=json.dumps(payload))
  685. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  686. def update_client(self, client_id, payload):
  687. """
  688. Update a client
  689. :param client_id: Client id
  690. :param payload: ClientRepresentation
  691. :return: Http response
  692. """
  693. params_path = {"realm-name": self.realm_name, "id": client_id}
  694. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  695. data=json.dumps(payload))
  696. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  697. def delete_client(self, client_id):
  698. """
  699. Get representation of the client
  700. ClientRepresentation
  701. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  702. :param client_id: keycloak client id (not oauth client-id)
  703. :return: Keycloak server response (ClientRepresentation)
  704. """
  705. params_path = {"realm-name": self.realm_name, "id": client_id}
  706. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  707. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  708. def get_client_installation_provider(self, client_id, provider_id):
  709. """
  710. Get content for given installation provider
  711. Related documentation:
  712. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_clients_resource
  713. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  714. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_serverinforepresentation
  715. :param client_id: Client id
  716. :param provider_id: provider id to specify response format
  717. """
  718. params_path = {"realm-name": self.realm_name, "id": client_id, "provider-id": provider_id}
  719. data_raw = self.raw_get(URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path))
  720. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  721. def get_realm_roles(self):
  722. """
  723. Get all roles for the realm or client
  724. RoleRepresentation
  725. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  726. :return: Keycloak server response (RoleRepresentation)
  727. """
  728. params_path = {"realm-name": self.realm_name}
  729. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  730. return raise_error_from_response(data_raw, KeycloakGetError)
  731. def get_realm_role_members(self, role_name, **query):
  732. """
  733. Get role members of realm by role name.
  734. :param role_name: Name of the role.
  735. :param query: Additional Query parameters (see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_roles_resource)
  736. :return: Keycloak Server Response (UserRepresentation)
  737. """
  738. params_path = {"realm-name": self.realm_name, "role-name":role_name}
  739. return self.__fetch_all(URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query)
  740. def get_client_roles(self, client_id):
  741. """
  742. Get all roles for the client
  743. :param client_id: id of client (not client-id)
  744. RoleRepresentation
  745. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  746. :return: Keycloak server response (RoleRepresentation)
  747. """
  748. params_path = {"realm-name": self.realm_name, "id": client_id}
  749. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  750. return raise_error_from_response(data_raw, KeycloakGetError)
  751. def get_client_role(self, client_id, role_name):
  752. """
  753. Get client role id by name
  754. This is required for further actions with this role.
  755. :param client_id: id of client (not client-id)
  756. :param role_name: roles name (not id!)
  757. RoleRepresentation
  758. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  759. :return: role_id
  760. """
  761. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  762. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  763. return raise_error_from_response(data_raw, KeycloakGetError)
  764. def get_client_role_id(self, client_id, role_name):
  765. """
  766. Warning: Deprecated
  767. Get client role id by name
  768. This is required for further actions with this role.
  769. :param client_id: id of client (not client-id)
  770. :param role_name: roles name (not id!)
  771. RoleRepresentation
  772. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  773. :return: role_id
  774. """
  775. role = self.get_client_role(client_id, role_name)
  776. return role.get("id")
  777. def create_client_role(self, client_role_id, payload, skip_exists=False):
  778. """
  779. Create a client role
  780. RoleRepresentation
  781. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  782. :param client_role_id: id of client (not client-id)
  783. :param payload: RoleRepresentation
  784. :param skip_exists: If true then do not raise an error if client role already exists
  785. :return: Keycloak server response (RoleRepresentation)
  786. """
  787. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  788. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  789. data=json.dumps(payload))
  790. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  791. def add_composite_client_roles_to_role(self, client_role_id, role_name, roles):
  792. """
  793. Add composite roles to client role
  794. :param client_role_id: id of client (not client-id)
  795. :param role_name: The name of the role
  796. :param roles: roles list or role (use RoleRepresentation) to be updated
  797. :return Keycloak server response
  798. """
  799. payload = roles if isinstance(roles, list) else [roles]
  800. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  801. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE.format(**params_path),
  802. data=json.dumps(payload))
  803. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  804. def delete_client_role(self, client_role_id, role_name):
  805. """
  806. Delete a client role
  807. RoleRepresentation
  808. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  809. :param client_role_id: id of client (not client-id)
  810. :param role_name: roles name (not id!)
  811. """
  812. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  813. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  814. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  815. def assign_client_role(self, user_id, client_id, roles):
  816. """
  817. Assign a client role to a user
  818. :param user_id: id of user
  819. :param client_id: id of client (not client-id)
  820. :param roles: roles list or role (use RoleRepresentation)
  821. :return Keycloak server response
  822. """
  823. payload = roles if isinstance(roles, list) else [roles]
  824. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  825. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  826. data=json.dumps(payload))
  827. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  828. def get_client_role_members(self, client_id, role_name, **query):
  829. """
  830. Get members by client role .
  831. :param client_id: The client id
  832. :param role_name: the name of role to be queried.
  833. :param query: Additional query parameters ( see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_clients_resource)
  834. :return: Keycloak server response (UserRepresentation)
  835. """
  836. params_path = {"realm-name": self.realm_name, "id":client_id, "role-name":role_name}
  837. return self.__fetch_all(URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path) , query)
  838. def create_realm_role(self, payload, skip_exists=False):
  839. """
  840. Create a new role for the realm or client
  841. :param payload: The role (use RoleRepresentation)
  842. :param skip_exists: If true then do not raise an error if realm role already exists
  843. :return Keycloak server response
  844. """
  845. params_path = {"realm-name": self.realm_name}
  846. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  847. data=json.dumps(payload))
  848. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  849. def get_realm_role(self, role_name):
  850. """
  851. Get realm role by role name
  852. :param role_name: role's name, not id!
  853. RoleRepresentation
  854. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  855. :return: role_id
  856. """
  857. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  858. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  859. return raise_error_from_response(data_raw, KeycloakGetError)
  860. def update_realm_role(self, role_name, payload):
  861. """
  862. Update a role for the realm by name
  863. :param role_name: The name of the role to be updated
  864. :param payload: The role (use RoleRepresentation)
  865. :return Keycloak server response
  866. """
  867. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  868. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  869. data=json.dumps(payload))
  870. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  871. def delete_realm_role(self, role_name):
  872. """
  873. Delete a role for the realm by name
  874. :param payload: The role name {'role-name':'name-of-the-role'}
  875. :return Keycloak server response
  876. """
  877. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  878. data_raw = self.connection.raw_delete(
  879. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  880. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  881. def add_composite_realm_roles_to_role(self, role_name, roles):
  882. """
  883. Add composite roles to the role
  884. :param role_name: The name of the role
  885. :param roles: roles list or role (use RoleRepresentation) to be updated
  886. :return Keycloak server response
  887. """
  888. payload = roles if isinstance(roles, list) else [roles]
  889. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  890. data_raw = self.raw_post(
  891. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  892. data=json.dumps(payload))
  893. return raise_error_from_response(data_raw, KeycloakGetError,
  894. expected_codes=[204])
  895. def remove_composite_realm_roles_to_role(self, role_name, roles):
  896. """
  897. Remove composite roles from the role
  898. :param role_name: The name of the role
  899. :param roles: roles list or role (use RoleRepresentation) to be removed
  900. :return Keycloak server response
  901. """
  902. payload = roles if isinstance(roles, list) else [roles]
  903. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  904. data_raw = self.raw_delete(
  905. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  906. data=json.dumps(payload))
  907. return raise_error_from_response(data_raw, KeycloakGetError,
  908. expected_codes=[204])
  909. def get_composite_realm_roles_of_role(self, role_name):
  910. """
  911. Get composite roles of the role
  912. :param role_name: The name of the role
  913. :return Keycloak server response (array RoleRepresentation)
  914. """
  915. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  916. data_raw = self.raw_get(
  917. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  918. return raise_error_from_response(data_raw, KeycloakGetError)
  919. def assign_realm_roles(self, user_id, client_id, roles):
  920. """
  921. Assign realm roles to a user
  922. :param user_id: id of user
  923. :param client_id: id of client containing role (not client-id)
  924. :param roles: roles list or role (use RoleRepresentation)
  925. :return Keycloak server response
  926. """
  927. payload = roles if isinstance(roles, list) else [roles]
  928. params_path = {"realm-name": self.realm_name, "id": user_id}
  929. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  930. data=json.dumps(payload))
  931. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  932. def get_realm_roles_of_user(self, user_id):
  933. """
  934. Get all realm roles for a user.
  935. :param user_id: id of user
  936. :return: Keycloak server response (array RoleRepresentation)
  937. """
  938. params_path = {"realm-name": self.realm_name, "id": user_id}
  939. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  940. return raise_error_from_response(data_raw, KeycloakGetError)
  941. def assign_group_realm_roles(self, group_id, roles):
  942. """
  943. Assign realm roles to a group
  944. :param group_id: id of groupp
  945. :param roles: roles list or role (use GroupRoleRepresentation)
  946. :return Keycloak server response
  947. """
  948. payload = roles if isinstance(roles, list) else [roles]
  949. params_path = {"realm-name": self.realm_name, "id": group_id}
  950. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  951. data=json.dumps(payload))
  952. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  953. def delete_group_realm_roles(self, group_id, roles):
  954. """
  955. Delete realm roles of a group
  956. :param group_id: id of group
  957. :param roles: roles list or role (use GroupRoleRepresentation)
  958. :return Keycloak server response
  959. """
  960. payload = roles if isinstance(roles, list) else [roles]
  961. params_path = {"realm-name": self.realm_name, "id": group_id}
  962. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  963. data=json.dumps(payload))
  964. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  965. def get_group_realm_roles(self, group_id):
  966. """
  967. Get all realm roles for a group.
  968. :param user_id: id of the group
  969. :return: Keycloak server response (array RoleRepresentation)
  970. """
  971. params_path = {"realm-name": self.realm_name, "id": group_id}
  972. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  973. return raise_error_from_response(data_raw, KeycloakGetError)
  974. def assign_group_client_roles(self, group_id, client_id, roles):
  975. """
  976. Assign client roles to a group
  977. :param group_id: id of group
  978. :param client_id: id of client (not client-id)
  979. :param roles: roles list or role (use GroupRoleRepresentation)
  980. :return Keycloak server response
  981. """
  982. payload = roles if isinstance(roles, list) else [roles]
  983. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  984. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  985. data=json.dumps(payload))
  986. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  987. def get_group_client_roles(self, group_id, client_id):
  988. """
  989. Get client roles of a group
  990. :param group_id: id of group
  991. :param client_id: id of client (not client-id)
  992. :return Keycloak server response
  993. """
  994. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  995. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  996. return raise_error_from_response(data_raw, KeycloakGetError)
  997. def delete_group_client_roles(self, group_id, client_id, roles):
  998. """
  999. Delete client roles of a group
  1000. :param group_id: id of group
  1001. :param client_id: id of client (not client-id)
  1002. :param roles: roles list or role (use GroupRoleRepresentation)
  1003. :return Keycloak server response (array RoleRepresentation)
  1004. """
  1005. payload = roles if isinstance(roles, list) else [roles]
  1006. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1007. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1008. data=json.dumps(payload))
  1009. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1010. def get_client_roles_of_user(self, user_id, client_id):
  1011. """
  1012. Get all client roles for a user.
  1013. :param user_id: id of user
  1014. :param client_id: id of client (not client-id)
  1015. :return: Keycloak server response (array RoleRepresentation)
  1016. """
  1017. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1018. def get_available_client_roles_of_user(self, user_id, client_id):
  1019. """
  1020. Get available client role-mappings for a user.
  1021. :param user_id: id of user
  1022. :param client_id: id of client (not client-id)
  1023. :return: Keycloak server response (array RoleRepresentation)
  1024. """
  1025. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1026. def get_composite_client_roles_of_user(self, user_id, client_id):
  1027. """
  1028. Get composite client role-mappings for a user.
  1029. :param user_id: id of user
  1030. :param client_id: id of client (not client-id)
  1031. :return: Keycloak server response (array RoleRepresentation)
  1032. """
  1033. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1034. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1035. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1036. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1037. return raise_error_from_response(data_raw, KeycloakGetError)
  1038. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1039. """
  1040. Delete client roles from a user.
  1041. :param user_id: id of user
  1042. :param client_id: id of client containing role (not client-id)
  1043. :param roles: roles list or role to delete (use RoleRepresentation)
  1044. :return: Keycloak server response
  1045. """
  1046. payload = roles if isinstance(roles, list) else [roles]
  1047. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1048. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1049. data=json.dumps(payload))
  1050. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1051. def get_authentication_flows(self):
  1052. """
  1053. Get authentication flows. Returns all flow details
  1054. AuthenticationFlowRepresentation
  1055. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1056. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1057. """
  1058. params_path = {"realm-name": self.realm_name}
  1059. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1060. return raise_error_from_response(data_raw, KeycloakGetError)
  1061. def get_authentication_flow_for_id(self, flow_id):
  1062. """
  1063. Get one authentication flow by it's id/alias. Returns all flow details
  1064. AuthenticationFlowRepresentation
  1065. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1066. :param flow_id: the id of a flow NOT it's alias
  1067. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1068. """
  1069. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1070. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1071. return raise_error_from_response(data_raw, KeycloakGetError)
  1072. def create_authentication_flow(self, payload, skip_exists=False):
  1073. """
  1074. Create a new authentication flow
  1075. AuthenticationFlowRepresentation
  1076. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1077. :param payload: AuthenticationFlowRepresentation
  1078. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1079. :return: Keycloak server response (RoleRepresentation)
  1080. """
  1081. params_path = {"realm-name": self.realm_name}
  1082. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1083. data=payload)
  1084. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1085. def copy_authentication_flow(self, payload, flow_alias):
  1086. """
  1087. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1088. :param payload: JSON containing 'newName' attribute
  1089. :param flow_alias: the flow alias
  1090. :return: Keycloak server response (RoleRepresentation)
  1091. """
  1092. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1093. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1094. data=payload)
  1095. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1096. def get_authentication_flow_executions(self, flow_alias):
  1097. """
  1098. Get authentication flow executions. Returns all execution steps
  1099. :param flow_alias: the flow alias
  1100. :return: Response(json)
  1101. """
  1102. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1103. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1104. return raise_error_from_response(data_raw, KeycloakGetError)
  1105. def update_authentication_flow_executions(self, payload, flow_alias):
  1106. """
  1107. Update an authentication flow execution
  1108. AuthenticationExecutionInfoRepresentation
  1109. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1110. :param payload: AuthenticationExecutionInfoRepresentation
  1111. :param flow_alias: The flow alias
  1112. :return: Keycloak server response
  1113. """
  1114. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1115. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1116. data=payload)
  1117. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1118. def create_authentication_flow_execution(self, payload, flow_alias):
  1119. """
  1120. Create an authentication flow execution
  1121. AuthenticationExecutionInfoRepresentation
  1122. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1123. :param payload: AuthenticationExecutionInfoRepresentation
  1124. :param flow_alias: The flow alias
  1125. :return: Keycloak server response
  1126. """
  1127. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1128. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1129. data=payload)
  1130. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1131. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1132. """
  1133. Create a new sub authentication flow for a given authentication flow
  1134. AuthenticationFlowRepresentation
  1135. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1136. :param payload: AuthenticationFlowRepresentation
  1137. :param flow_alias: The flow alias
  1138. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1139. :return: Keycloak server response (RoleRepresentation)
  1140. """
  1141. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1142. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1143. data=payload)
  1144. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1145. def get_authenticator_config(self, config_id):
  1146. """
  1147. Get authenticator configuration. Returns all configuration details.
  1148. :param config_id: Authenticator config id
  1149. :return: Response(json)
  1150. """
  1151. params_path = {"realm-name": self.realm_name, "id": config_id}
  1152. data_raw = self.raw_get(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1153. return raise_error_from_response(data_raw, KeycloakGetError)
  1154. def update_authenticator_config(self, payload, config_id):
  1155. """
  1156. Update an authenticator configuration.
  1157. AuthenticatorConfigRepresentation
  1158. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticatorconfigrepresentation
  1159. :param payload: AuthenticatorConfigRepresentation
  1160. :param config_id: Authenticator config id
  1161. :return: Response(json)
  1162. """
  1163. params_path = {"realm-name": self.realm_name, "id": config_id}
  1164. data_raw = self.raw_put(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1165. data=json.dumps(payload))
  1166. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1167. def delete_authenticator_config(self, config_id):
  1168. """
  1169. Delete a authenticator configuration.
  1170. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource
  1171. :param config_id: Authenticator config id
  1172. :return: Keycloak server Response
  1173. """
  1174. params_path = {"realm-name": self.realm_name, "id": config_id}
  1175. data_raw = self.raw_delete(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1176. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1177. def sync_users(self, storage_id, action):
  1178. """
  1179. Function to trigger user sync from provider
  1180. :param storage_id: The id of the user storage provider
  1181. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1182. :return:
  1183. """
  1184. data = {'action': action}
  1185. params_query = {"action": action}
  1186. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1187. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1188. data=json.dumps(data), **params_query)
  1189. return raise_error_from_response(data_raw, KeycloakGetError)
  1190. def get_client_scopes(self):
  1191. """
  1192. Get representation of the client scopes for the realm where we are connected to
  1193. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1194. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1195. """
  1196. params_path = {"realm-name": self.realm_name}
  1197. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1198. return raise_error_from_response(data_raw, KeycloakGetError)
  1199. def get_client_scope(self, client_scope_id):
  1200. """
  1201. Get representation of the client scopes for the realm where we are connected to
  1202. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1203. :param client_scope_id: The id of the client scope
  1204. :return: Keycloak server response (ClientScopeRepresentation)
  1205. """
  1206. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1207. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1208. return raise_error_from_response(data_raw, KeycloakGetError)
  1209. def create_client_scope(self, payload, skip_exists=False):
  1210. """
  1211. Create a client scope
  1212. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1213. :param payload: ClientScopeRepresentation
  1214. :param skip_exists: If true then do not raise an error if client scope already exists
  1215. :return: Keycloak server response (ClientScopeRepresentation)
  1216. """
  1217. params_path = {"realm-name": self.realm_name}
  1218. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1219. data=json.dumps(payload))
  1220. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1221. def update_client_scope(self, client_scope_id, payload):
  1222. """
  1223. Update a client scope
  1224. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_client_scopes_resource
  1225. :param client_scope_id: The id of the client scope
  1226. :param payload: ClientScopeRepresentation
  1227. :return: Keycloak server response (ClientScopeRepresentation)
  1228. """
  1229. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1230. data_raw = self.raw_put(URL_ADMIN_CLIENT_SCOPE.format(**params_path),
  1231. data=json.dumps(payload))
  1232. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1233. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1234. """
  1235. Add a mapper to a client scope
  1236. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1237. :param client_scope_id: The id of the client scope
  1238. :param payload: ProtocolMapperRepresentation
  1239. :return: Keycloak server Response
  1240. """
  1241. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1242. data_raw = self.raw_post(
  1243. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1244. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1245. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1246. """
  1247. Delete a mapper from a client scope
  1248. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1249. :param client_scope_id: The id of the client scope
  1250. :param payload: ProtocolMapperRepresentation
  1251. :return: Keycloak server Response
  1252. """
  1253. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1254. "protocol-mapper-id": protocol_mppaer_id}
  1255. data_raw = self.raw_delete(
  1256. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1257. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1258. def add_mapper_to_client(self, client_id, payload):
  1259. """
  1260. Add a mapper to a client
  1261. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1262. :param client_id: The id of the client
  1263. :param payload: ProtocolMapperRepresentation
  1264. :return: Keycloak server Response
  1265. """
  1266. params_path = {"realm-name": self.realm_name, "id": client_id}
  1267. data_raw = self.raw_post(
  1268. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1269. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1270. def generate_client_secrets(self, client_id):
  1271. """
  1272. Generate a new secret for the client
  1273. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1274. :param client_id: id of client (not client-id)
  1275. :return: Keycloak server response (ClientRepresentation)
  1276. """
  1277. params_path = {"realm-name": self.realm_name, "id": client_id}
  1278. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1279. return raise_error_from_response(data_raw, KeycloakGetError)
  1280. def get_client_secrets(self, client_id):
  1281. """
  1282. Get representation of the client secrets
  1283. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1284. :param client_id: id of client (not client-id)
  1285. :return: Keycloak server response (ClientRepresentation)
  1286. """
  1287. params_path = {"realm-name": self.realm_name, "id": client_id}
  1288. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1289. return raise_error_from_response(data_raw, KeycloakGetError)
  1290. def get_components(self, query=None):
  1291. """
  1292. Return a list of components, filtered according to query parameters
  1293. ComponentRepresentation
  1294. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1295. :param query: Query parameters (optional)
  1296. :return: components list
  1297. """
  1298. params_path = {"realm-name": self.realm_name}
  1299. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1300. data=None, **query)
  1301. return raise_error_from_response(data_raw, KeycloakGetError)
  1302. def create_component(self, payload):
  1303. """
  1304. Create a new component.
  1305. ComponentRepresentation
  1306. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1307. :param payload: ComponentRepresentation
  1308. :return: UserRepresentation
  1309. """
  1310. params_path = {"realm-name": self.realm_name}
  1311. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1312. data=json.dumps(payload))
  1313. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1314. def get_component(self, component_id):
  1315. """
  1316. Get representation of the component
  1317. :param component_id: Component id
  1318. ComponentRepresentation
  1319. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1320. :return: ComponentRepresentation
  1321. """
  1322. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1323. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1324. return raise_error_from_response(data_raw, KeycloakGetError)
  1325. def update_component(self, component_id, payload):
  1326. """
  1327. Update the component
  1328. :param component_id: Component id
  1329. :param payload: ComponentRepresentation
  1330. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1331. :return: Http response
  1332. """
  1333. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1334. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1335. data=json.dumps(payload))
  1336. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1337. def delete_component(self, component_id):
  1338. """
  1339. Delete the component
  1340. :param component_id: Component id
  1341. :return: Http response
  1342. """
  1343. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1344. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1345. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1346. def get_keys(self):
  1347. """
  1348. Return a list of keys, filtered according to query parameters
  1349. KeysMetadataRepresentation
  1350. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1351. :return: keys list
  1352. """
  1353. params_path = {"realm-name": self.realm_name}
  1354. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1355. data=None)
  1356. return raise_error_from_response(data_raw, KeycloakGetError)
  1357. def raw_get(self, *args, **kwargs):
  1358. """
  1359. Calls connection.raw_get.
  1360. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1361. and try *get* once more.
  1362. """
  1363. r = self.connection.raw_get(*args, **kwargs)
  1364. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1365. self.refresh_token()
  1366. return self.connection.raw_get(*args, **kwargs)
  1367. return r
  1368. def raw_post(self, *args, **kwargs):
  1369. """
  1370. Calls connection.raw_post.
  1371. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1372. and try *post* once more.
  1373. """
  1374. r = self.connection.raw_post(*args, **kwargs)
  1375. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1376. self.refresh_token()
  1377. return self.connection.raw_post(*args, **kwargs)
  1378. return r
  1379. def raw_put(self, *args, **kwargs):
  1380. """
  1381. Calls connection.raw_put.
  1382. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1383. and try *put* once more.
  1384. """
  1385. r = self.connection.raw_put(*args, **kwargs)
  1386. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1387. self.refresh_token()
  1388. return self.connection.raw_put(*args, **kwargs)
  1389. return r
  1390. def raw_delete(self, *args, **kwargs):
  1391. """
  1392. Calls connection.raw_delete.
  1393. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1394. and try *delete* once more.
  1395. """
  1396. r = self.connection.raw_delete(*args, **kwargs)
  1397. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1398. self.refresh_token()
  1399. return self.connection.raw_delete(*args, **kwargs)
  1400. return r
  1401. def get_token(self):
  1402. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1403. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1404. client_secret_key=self.client_secret_key,
  1405. custom_headers=self.custom_headers)
  1406. grant_type = ["password"]
  1407. if self.client_secret_key:
  1408. grant_type = ["client_credentials"]
  1409. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1410. headers = {
  1411. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1412. 'Content-Type': 'application/json'
  1413. }
  1414. if self.custom_headers is not None:
  1415. # merge custom headers to main headers
  1416. headers.update(self.custom_headers)
  1417. self._connection = ConnectionManager(base_url=self.server_url,
  1418. headers=headers,
  1419. timeout=60,
  1420. verify=self.verify)
  1421. def refresh_token(self):
  1422. refresh_token = self.token.get('refresh_token')
  1423. try:
  1424. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1425. except KeycloakGetError as e:
  1426. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1427. b'Token is not active' in e.response_body):
  1428. self.get_token()
  1429. else:
  1430. raise
  1431. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))