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.

1451 lines
55 KiB

7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
5 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
7 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
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
4 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, URL_ADMIN_REALM_ROLES_ROLE_BY_NAME
  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, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS
  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.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.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 update_realm_role(self, role_name, payload):
  738. """
  739. Update a role for the realm by name
  740. :param role_name: The name of the role to be updated
  741. :param payload: The role (use RoleRepresentation)
  742. :return Keycloak server response
  743. """
  744. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  745. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  746. data=json.dumps(payload))
  747. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  748. def delete_realm_role(self, role_name):
  749. """
  750. Delete a role for the realm by name
  751. :param payload: The role name {'role-name':'name-of-the-role'}
  752. :return Keycloak server response
  753. """
  754. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  755. data_raw = self.connection.raw_delete(
  756. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  757. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  758. def assign_realm_roles(self, user_id, client_id, roles):
  759. """
  760. Assign realm roles to a user
  761. :param user_id: id of user
  762. :param client_id: id of client containing role (not client-id)
  763. :param roles: roles list or role (use RoleRepresentation)
  764. :return Keycloak server response
  765. """
  766. payload = roles if isinstance(roles, list) else [roles]
  767. params_path = {"realm-name": self.realm_name, "id": user_id}
  768. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  769. data=json.dumps(payload))
  770. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  771. def assign_group_realm_roles(self, group_id, roles):
  772. """
  773. Assign realm roles to a group
  774. :param group_id: id of groupp
  775. :param roles: roles list or role (use GroupRoleRepresentation)
  776. :return Keycloak server response
  777. """
  778. payload = roles if isinstance(roles, list) else [roles]
  779. params_path = {"realm-name": self.realm_name, "id": group_id}
  780. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  781. data=json.dumps(payload))
  782. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  783. def delete_group_realm_roles(self, group_id, roles):
  784. """
  785. Delete realm roles of a group
  786. :param group_id: id of group
  787. :param roles: roles list or role (use GroupRoleRepresentation)
  788. :return Keycloak server response
  789. """
  790. payload = roles if isinstance(roles, list) else [roles]
  791. params_path = {"realm-name": self.realm_name, "id": group_id}
  792. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  793. data=json.dumps(payload))
  794. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  795. def get_group_realm_roles(self, group_id):
  796. """
  797. Get all realm roles for a group.
  798. :param user_id: id of the group
  799. :return: Keycloak server response (array RoleRepresentation)
  800. """
  801. params_path = {"realm-name": self.realm_name, "id": group_id}
  802. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  803. return raise_error_from_response(data_raw, KeycloakGetError)
  804. def assign_group_client_roles(self, group_id, client_id, roles):
  805. """
  806. Assign client roles to a group
  807. :param group_id: id of group
  808. :param client_id: id of client (not client-id)
  809. :param roles: roles list or role (use GroupRoleRepresentation)
  810. :return Keycloak server response
  811. """
  812. payload = roles if isinstance(roles, list) else [roles]
  813. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  814. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  815. data=json.dumps(payload))
  816. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  817. def delete_group_client_roles(self, group_id, client_id, roles):
  818. """
  819. Delete client roles of a group
  820. :param group_id: id of group
  821. :param client_id: id of client (not client-id)
  822. :param roles: roles list or role (use GroupRoleRepresentation)
  823. :return Keycloak server response
  824. """
  825. payload = roles if isinstance(roles, list) else [roles]
  826. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  827. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  828. return raise_error_from_response(data_raw, KeycloakGetError)
  829. def get_group_client_roles(self, group_id, client_id, roles):
  830. """
  831. Get client roles of a group
  832. :param group_id: id of group
  833. :param client_id: id of client (not client-id)
  834. :param roles: roles list or role (use GroupRoleRepresentation)
  835. :return Keycloak server response (array RoleRepresentation)
  836. """
  837. payload = roles if isinstance(roles, list) else [roles]
  838. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  839. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  840. data=json.dumps(payload))
  841. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  842. def get_client_roles_of_user(self, user_id, client_id):
  843. """
  844. Get all client roles for a user.
  845. :param user_id: id of user
  846. :param client_id: id of client (not client-id)
  847. :return: Keycloak server response (array RoleRepresentation)
  848. """
  849. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  850. def get_available_client_roles_of_user(self, user_id, client_id):
  851. """
  852. Get available client role-mappings for a user.
  853. :param user_id: id of user
  854. :param client_id: id of client (not client-id)
  855. :return: Keycloak server response (array RoleRepresentation)
  856. """
  857. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  858. def get_composite_client_roles_of_user(self, user_id, client_id):
  859. """
  860. Get composite client role-mappings for a user.
  861. :param user_id: id of user
  862. :param client_id: id of client (not client-id)
  863. :return: Keycloak server response (array RoleRepresentation)
  864. """
  865. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  866. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  867. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  868. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  869. return raise_error_from_response(data_raw, KeycloakGetError)
  870. def delete_client_roles_of_user(self, user_id, client_id, roles):
  871. """
  872. Delete client roles from a user.
  873. :param user_id: id of user
  874. :param client_id: id of client containing role (not client-id)
  875. :param roles: roles list or role to delete (use RoleRepresentation)
  876. :return: Keycloak server response
  877. """
  878. payload = roles if isinstance(roles, list) else [roles]
  879. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  880. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  881. data=json.dumps(payload))
  882. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  883. def get_authentication_flows(self):
  884. """
  885. Get authentication flows. Returns all flow details
  886. AuthenticationFlowRepresentation
  887. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  888. :return: Keycloak server response (AuthenticationFlowRepresentation)
  889. """
  890. params_path = {"realm-name": self.realm_name}
  891. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  892. return raise_error_from_response(data_raw, KeycloakGetError)
  893. def create_authentication_flow(self, payload, skip_exists=False):
  894. """
  895. Create a new authentication flow
  896. AuthenticationFlowRepresentation
  897. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  898. :param payload: AuthenticationFlowRepresentation
  899. :param skip_exists: If true then do not raise an error if authentication flow already exists
  900. :return: Keycloak server response (RoleRepresentation)
  901. """
  902. params_path = {"realm-name": self.realm_name}
  903. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  904. data=payload)
  905. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  906. def get_authentication_flow_executions(self, flow_alias):
  907. """
  908. Get authentication flow executions. Returns all execution steps
  909. :param flow_alias: the flow alias
  910. :return: Response(json)
  911. """
  912. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  913. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  914. return raise_error_from_response(data_raw, KeycloakGetError)
  915. def update_authentication_flow_executions(self, payload, flow_alias):
  916. """
  917. Update an authentication flow execution
  918. AuthenticationExecutionInfoRepresentation
  919. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  920. :param payload: AuthenticationExecutionInfoRepresentation
  921. :param flow_alias: The flow alias
  922. :return: Keycloak server response
  923. """
  924. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  925. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  926. data=payload)
  927. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  928. def sync_users(self, storage_id, action):
  929. """
  930. Function to trigger user sync from provider
  931. :param storage_id: The id of the user storage provider
  932. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  933. :return:
  934. """
  935. data = {'action': action}
  936. params_query = {"action": action}
  937. params_path = {"realm-name": self.realm_name, "id": storage_id}
  938. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  939. data=json.dumps(data), **params_query)
  940. return raise_error_from_response(data_raw, KeycloakGetError)
  941. def get_client_scopes(self):
  942. """
  943. Get representation of the client scopes for the realm where we are connected to
  944. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  945. :return: Keycloak server response Array of (ClientScopeRepresentation)
  946. """
  947. params_path = {"realm-name": self.realm_name}
  948. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  949. return raise_error_from_response(data_raw, KeycloakGetError)
  950. def get_client_scope(self, client_scope_id):
  951. """
  952. Get representation of the client scopes for the realm where we are connected to
  953. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  954. :param client_scope_id: The id of the client scope
  955. :return: Keycloak server response (ClientScopeRepresentation)
  956. """
  957. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  958. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  959. return raise_error_from_response(data_raw, KeycloakGetError)
  960. def add_mapper_to_client_scope(self, client_scope_id, payload):
  961. """
  962. Add a mapper to a client scope
  963. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  964. :param client_scope_id: The id of the client scope
  965. :param payload: ProtocolMapperRepresentation
  966. :return: Keycloak server Response
  967. """
  968. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  969. data_raw = self.raw_post(
  970. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  971. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  972. def generate_client_secrets(self, client_id):
  973. """
  974. Generate a new secret for the client
  975. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  976. :param client_id: id of client (not client-id)
  977. :return: Keycloak server response (ClientRepresentation)
  978. """
  979. params_path = {"realm-name": self.realm_name, "id": client_id}
  980. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  981. return raise_error_from_response(data_raw, KeycloakGetError)
  982. def get_client_secrets(self, client_id):
  983. """
  984. Get representation of the client secrets
  985. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  986. :param client_id: id of client (not client-id)
  987. :return: Keycloak server response (ClientRepresentation)
  988. """
  989. params_path = {"realm-name": self.realm_name, "id": client_id}
  990. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  991. return raise_error_from_response(data_raw, KeycloakGetError)
  992. def get_components(self, query=None):
  993. """
  994. Return a list of components, filtered according to query parameters
  995. ComponentRepresentation
  996. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  997. :param query: Query parameters (optional)
  998. :return: components list
  999. """
  1000. params_path = {"realm-name": self.realm_name}
  1001. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1002. data=None, **query)
  1003. return raise_error_from_response(data_raw, KeycloakGetError)
  1004. def create_component(self, payload):
  1005. """
  1006. Create a new component.
  1007. ComponentRepresentation
  1008. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1009. :param payload: ComponentRepresentation
  1010. :return: UserRepresentation
  1011. """
  1012. params_path = {"realm-name": self.realm_name}
  1013. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1014. data=json.dumps(payload))
  1015. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  1016. def get_component(self, component_id):
  1017. """
  1018. Get representation of the component
  1019. :param component_id: Component id
  1020. ComponentRepresentation
  1021. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1022. :return: ComponentRepresentation
  1023. """
  1024. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1025. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1026. return raise_error_from_response(data_raw, KeycloakGetError)
  1027. def update_component(self, component_id, payload):
  1028. """
  1029. Update the component
  1030. :param component_id: Component id
  1031. :param payload: ComponentRepresentation
  1032. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1033. :return: Http response
  1034. """
  1035. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1036. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1037. data=json.dumps(payload))
  1038. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  1039. def delete_component(self, component_id):
  1040. """
  1041. Delete the component
  1042. :param component_id: Component id
  1043. :return: Http response
  1044. """
  1045. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1046. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1047. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  1048. def get_keys(self):
  1049. """
  1050. Return a list of keys, filtered according to query parameters
  1051. KeysMetadataRepresentation
  1052. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1053. :return: keys list
  1054. """
  1055. params_path = {"realm-name": self.realm_name}
  1056. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1057. data=None)
  1058. return raise_error_from_response(data_raw, KeycloakGetError)
  1059. def raw_get(self, *args, **kwargs):
  1060. """
  1061. Calls connection.raw_get.
  1062. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1063. and try *get* once more.
  1064. """
  1065. r = self.connection.raw_get(*args, **kwargs)
  1066. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1067. self.refresh_token()
  1068. return self.connection.raw_get(*args, **kwargs)
  1069. return r
  1070. def raw_post(self, *args, **kwargs):
  1071. """
  1072. Calls connection.raw_post.
  1073. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1074. and try *post* once more.
  1075. """
  1076. r = self.connection.raw_post(*args, **kwargs)
  1077. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1078. self.refresh_token()
  1079. return self.connection.raw_post(*args, **kwargs)
  1080. return r
  1081. def raw_put(self, *args, **kwargs):
  1082. """
  1083. Calls connection.raw_put.
  1084. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1085. and try *put* once more.
  1086. """
  1087. r = self.connection.raw_put(*args, **kwargs)
  1088. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1089. self.refresh_token()
  1090. return self.connection.raw_put(*args, **kwargs)
  1091. return r
  1092. def raw_delete(self, *args, **kwargs):
  1093. """
  1094. Calls connection.raw_delete.
  1095. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1096. and try *delete* once more.
  1097. """
  1098. r = self.connection.raw_delete(*args, **kwargs)
  1099. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1100. self.refresh_token()
  1101. return self.connection.raw_delete(*args, **kwargs)
  1102. return r
  1103. def get_token(self):
  1104. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1105. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1106. client_secret_key=self.client_secret_key,
  1107. custom_headers=self.custom_headers)
  1108. grant_type = ["password"]
  1109. if self.client_secret_key:
  1110. grant_type = ["client_credentials"]
  1111. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1112. headers = {
  1113. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1114. 'Content-Type': 'application/json'
  1115. }
  1116. if self.custom_headers is not None:
  1117. # merge custom headers to main headers
  1118. headers.update(self.custom_headers)
  1119. self._connection = ConnectionManager(base_url=self.server_url,
  1120. headers=headers,
  1121. timeout=60,
  1122. verify=self.verify)
  1123. def refresh_token(self):
  1124. refresh_token = self.token.get('refresh_token')
  1125. try:
  1126. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1127. except KeycloakGetError as e:
  1128. if e.response_code == 400 and b'Refresh token expired' in e.response_body:
  1129. self.get_token()
  1130. else:
  1131. raise
  1132. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))