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.

4607 lines
170 KiB

7 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
3 years ago
3 years ago
3 years ago
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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
  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. """The keycloak admin module."""
  26. import copy
  27. import json
  28. from builtins import isinstance
  29. from typing import Optional
  30. import deprecation
  31. from requests_toolbelt import MultipartEncoder
  32. from . import urls_patterns
  33. from ._version import __version__
  34. from .exceptions import (
  35. KeycloakDeleteError,
  36. KeycloakGetError,
  37. KeycloakPostError,
  38. KeycloakPutError,
  39. raise_error_from_response,
  40. )
  41. from .openid_connection import KeycloakOpenIDConnection
  42. class KeycloakAdmin:
  43. """Keycloak Admin client.
  44. :param server_url: Keycloak server url
  45. :type server_url: str
  46. :param username: admin username
  47. :type username: str
  48. :param password: admin password
  49. :type password: str
  50. :param token: access and refresh tokens
  51. :type token: dict
  52. :param totp: Time based OTP
  53. :type totp: str
  54. :param realm_name: realm name
  55. :type realm_name: str
  56. :param client_id: client id
  57. :type client_id: str
  58. :param verify: Boolean value to enable or disable certificate validation or a string
  59. containing a path to a CA bundle to use
  60. :type verify: Union[bool,str]
  61. :param client_secret_key: client secret key
  62. (optional, required only for access type confidential)
  63. :type client_secret_key: str
  64. :param custom_headers: dict of custom header to pass to each HTML request
  65. :type custom_headers: dict
  66. :param user_realm_name: The realm name of the user, if different from realm_name
  67. :type user_realm_name: str
  68. :param auto_refresh_token: list of methods that allows automatic token refresh.
  69. Ex: ['get', 'put', 'post', 'delete']
  70. :type auto_refresh_token: list
  71. :param timeout: connection timeout in seconds
  72. :type timeout: int
  73. :param connection: A KeycloakOpenIDConnection as an alternative to individual params.
  74. :type connection: KeycloakOpenIDConnection
  75. """
  76. PAGE_SIZE = 100
  77. _auto_refresh_token = None
  78. _connection: Optional[KeycloakOpenIDConnection] = None
  79. def __init__(
  80. self,
  81. server_url=None,
  82. username=None,
  83. password=None,
  84. token=None,
  85. totp=None,
  86. realm_name="master",
  87. client_id="admin-cli",
  88. verify=True,
  89. client_secret_key=None,
  90. custom_headers=None,
  91. user_realm_name=None,
  92. auto_refresh_token=None,
  93. timeout=60,
  94. connection: Optional[KeycloakOpenIDConnection] = None,
  95. ):
  96. """Init method.
  97. :param server_url: Keycloak server url
  98. :type server_url: str
  99. :param username: admin username
  100. :type username: str
  101. :param password: admin password
  102. :type password: str
  103. :param token: access and refresh tokens
  104. :type token: dict
  105. :param totp: Time based OTP
  106. :type totp: str
  107. :param realm_name: realm name
  108. :type realm_name: str
  109. :param client_id: client id
  110. :type client_id: str
  111. :param verify: Boolean value to enable or disable certificate validation or a string
  112. containing a path to a CA bundle to use
  113. :type verify: Union[bool,str]
  114. :param client_secret_key: client secret key
  115. (optional, required only for access type confidential)
  116. :type client_secret_key: str
  117. :param custom_headers: dict of custom header to pass to each HTML request
  118. :type custom_headers: dict
  119. :param user_realm_name: The realm name of the user, if different from realm_name
  120. :type user_realm_name: str
  121. :param auto_refresh_token: list of methods that allows automatic token refresh.
  122. Ex: ['get', 'put', 'post', 'delete']
  123. :type auto_refresh_token: list
  124. :param timeout: connection timeout in seconds
  125. :type timeout: int
  126. :param connection: An OpenID Connection as an alternative to individual params.
  127. :type connection: KeycloakOpenIDConnection
  128. """
  129. self.connection = connection or KeycloakOpenIDConnection(
  130. server_url=server_url,
  131. username=username,
  132. password=password,
  133. token=token,
  134. totp=totp,
  135. realm_name=realm_name,
  136. client_id=client_id,
  137. verify=verify,
  138. client_secret_key=client_secret_key,
  139. user_realm_name=user_realm_name,
  140. custom_headers=custom_headers,
  141. timeout=timeout,
  142. )
  143. if auto_refresh_token is not None:
  144. self.auto_refresh_token = auto_refresh_token
  145. @property
  146. @deprecation.deprecated(
  147. deprecated_in="2.13.0",
  148. removed_in="4.0.0",
  149. current_version=__version__,
  150. details="Use the connection.server_url property instead",
  151. )
  152. def server_url(self):
  153. """Get server url.
  154. :returns: Keycloak server url
  155. :rtype: str
  156. """
  157. return self.connection.server_url
  158. @server_url.setter
  159. @deprecation.deprecated(
  160. deprecated_in="2.13.0",
  161. removed_in="4.0.0",
  162. current_version=__version__,
  163. details="Use the connection.server_url property instead",
  164. )
  165. def server_url(self, value):
  166. self.connection.server_url = value
  167. @property
  168. @deprecation.deprecated(
  169. deprecated_in="2.13.0",
  170. removed_in="4.0.0",
  171. current_version=__version__,
  172. details="Use the connection.realm_name property instead",
  173. )
  174. def realm_name(self):
  175. """Get realm name.
  176. :returns: Realm name
  177. :rtype: str
  178. """
  179. return self.connection.realm_name
  180. @realm_name.setter
  181. @deprecation.deprecated(
  182. deprecated_in="2.13.0",
  183. removed_in="4.0.0",
  184. current_version=__version__,
  185. details="Use the connection.realm_name property instead",
  186. )
  187. def realm_name(self, value):
  188. self.connection.realm_name = value
  189. @property
  190. def connection(self) -> KeycloakOpenIDConnection:
  191. """Get connection.
  192. :returns: Connection manager
  193. :rtype: KeycloakOpenIDConnection
  194. """
  195. return self._connection
  196. @connection.setter
  197. def connection(self, value: KeycloakOpenIDConnection) -> None:
  198. self._connection = value
  199. @property
  200. @deprecation.deprecated(
  201. deprecated_in="2.13.0",
  202. removed_in="4.0.0",
  203. current_version=__version__,
  204. details="Use the connection.client_id property instead",
  205. )
  206. def client_id(self):
  207. """Get client id.
  208. :returns: Client id
  209. :rtype: str
  210. """
  211. return self.connection.client_id
  212. @client_id.setter
  213. @deprecation.deprecated(
  214. deprecated_in="2.13.0",
  215. removed_in="4.0.0",
  216. current_version=__version__,
  217. details="Use the connection.client_id property instead",
  218. )
  219. def client_id(self, value):
  220. self.connection.client_id = value
  221. @property
  222. @deprecation.deprecated(
  223. deprecated_in="2.13.0",
  224. removed_in="4.0.0",
  225. current_version=__version__,
  226. details="Use the connection.client_secret_key property instead",
  227. )
  228. def client_secret_key(self):
  229. """Get client secret key.
  230. :returns: Client secret key
  231. :rtype: str
  232. """
  233. return self.connection.client_secret_key
  234. @client_secret_key.setter
  235. @deprecation.deprecated(
  236. deprecated_in="2.13.0",
  237. removed_in="4.0.0",
  238. current_version=__version__,
  239. details="Use the connection.client_secret_key property instead",
  240. )
  241. def client_secret_key(self, value):
  242. self.connection.client_secret_key = value
  243. @property
  244. @deprecation.deprecated(
  245. deprecated_in="2.13.0",
  246. removed_in="4.0.0",
  247. current_version=__version__,
  248. details="Use the connection.verify property instead",
  249. )
  250. def verify(self):
  251. """Get verify.
  252. :returns: Verify indicator
  253. :rtype: bool
  254. """
  255. return self.connection.verify
  256. @verify.setter
  257. @deprecation.deprecated(
  258. deprecated_in="2.13.0",
  259. removed_in="4.0.0",
  260. current_version=__version__,
  261. details="Use the connection.verify property instead",
  262. )
  263. def verify(self, value):
  264. self.connection.verify = value
  265. @property
  266. @deprecation.deprecated(
  267. deprecated_in="2.13.0",
  268. removed_in="4.0.0",
  269. current_version=__version__,
  270. details="Use the connection.username property instead",
  271. )
  272. def username(self):
  273. """Get username.
  274. :returns: Admin username
  275. :rtype: str
  276. """
  277. return self.connection.username
  278. @username.setter
  279. @deprecation.deprecated(
  280. deprecated_in="2.13.0",
  281. removed_in="4.0.0",
  282. current_version=__version__,
  283. details="Use the connection.username property instead",
  284. )
  285. def username(self, value):
  286. self.connection.username = value
  287. @property
  288. @deprecation.deprecated(
  289. deprecated_in="2.13.0",
  290. removed_in="4.0.0",
  291. current_version=__version__,
  292. details="Use the connection.password property instead",
  293. )
  294. def password(self):
  295. """Get password.
  296. :returns: Admin password
  297. :rtype: str
  298. """
  299. return self.connection.password
  300. @password.setter
  301. @deprecation.deprecated(
  302. deprecated_in="2.13.0",
  303. removed_in="4.0.0",
  304. current_version=__version__,
  305. details="Use the connection.password property instead",
  306. )
  307. def password(self, value):
  308. self.connection.password = value
  309. @property
  310. @deprecation.deprecated(
  311. deprecated_in="2.13.0",
  312. removed_in="4.0.0",
  313. current_version=__version__,
  314. details="Use the connection.totp property instead",
  315. )
  316. def totp(self):
  317. """Get totp.
  318. :returns: TOTP
  319. :rtype: str
  320. """
  321. return self.connection.totp
  322. @totp.setter
  323. @deprecation.deprecated(
  324. deprecated_in="2.13.0",
  325. removed_in="4.0.0",
  326. current_version=__version__,
  327. details="Use the connection.totp property instead",
  328. )
  329. def totp(self, value):
  330. self.connection.totp = value
  331. @property
  332. @deprecation.deprecated(
  333. deprecated_in="2.13.0",
  334. removed_in="4.0.0",
  335. current_version=__version__,
  336. details="Use the connection.token property instead",
  337. )
  338. def token(self):
  339. """Get token.
  340. :returns: Access and refresh token
  341. :rtype: dict
  342. """
  343. return self.connection.token
  344. @token.setter
  345. @deprecation.deprecated(
  346. deprecated_in="2.13.0",
  347. removed_in="4.0.0",
  348. current_version=__version__,
  349. details="Use the connection.token property instead",
  350. )
  351. def token(self, value):
  352. self.connection.token = value
  353. @property
  354. @deprecation.deprecated(
  355. deprecated_in="2.13.0",
  356. removed_in="4.0.0",
  357. current_version=__version__,
  358. details="Use the connection.user_realm_name property instead",
  359. )
  360. def user_realm_name(self):
  361. """Get user realm name.
  362. :returns: User realm name
  363. :rtype: str
  364. """
  365. return self.connection.user_realm_name
  366. @user_realm_name.setter
  367. @deprecation.deprecated(
  368. deprecated_in="2.13.0",
  369. removed_in="4.0.0",
  370. current_version=__version__,
  371. details="Use the connection.user_realm_name property instead",
  372. )
  373. def user_realm_name(self, value):
  374. self.connection.user_realm_name = value
  375. @property
  376. @deprecation.deprecated(
  377. deprecated_in="2.13.0",
  378. removed_in="4.0.0",
  379. current_version=__version__,
  380. details="Use the connection.custom_headers property instead",
  381. )
  382. def custom_headers(self):
  383. """Get custom headers.
  384. :returns: Custom headers
  385. :rtype: dict
  386. """
  387. return self.connection.custom_headers
  388. @custom_headers.setter
  389. @deprecation.deprecated(
  390. deprecated_in="2.13.0",
  391. removed_in="4.0.0",
  392. current_version=__version__,
  393. details="Use the connection.custom_headers property instead",
  394. )
  395. def custom_headers(self, value):
  396. self.connection.custom_headers = value
  397. @property
  398. @deprecation.deprecated(
  399. deprecated_in="2.13.0",
  400. removed_in="4.0.0",
  401. current_version=__version__,
  402. details="Auto-refresh will be implicitly set for all requests",
  403. )
  404. def auto_refresh_token(self):
  405. """Get auto refresh token.
  406. :returns: List of methods for automatic token refresh
  407. :rtype: list
  408. """
  409. return self._auto_refresh_token
  410. @auto_refresh_token.setter
  411. @deprecation.deprecated(
  412. deprecated_in="2.13.0",
  413. removed_in="4.0.0",
  414. current_version=__version__,
  415. details="Auto-refresh will be implicitly set for all requests",
  416. )
  417. def auto_refresh_token(self, value):
  418. self._auto_refresh_token = value or []
  419. def __fetch_all(self, url, query=None):
  420. """Paginate over get requests.
  421. Wrapper function to paginate GET requests.
  422. :param url: The url on which the query is executed
  423. :type url: str
  424. :param query: Existing query parameters (optional)
  425. :type query: dict
  426. :return: Combined results of paginated queries
  427. :rtype: list
  428. """
  429. results = []
  430. # initialize query if it was called with None
  431. if not query:
  432. query = {}
  433. page = 0
  434. query["max"] = self.PAGE_SIZE
  435. # fetch until we can
  436. while True:
  437. query["first"] = page * self.PAGE_SIZE
  438. partial_results = raise_error_from_response(
  439. self.connection.raw_get(url, **query), KeycloakGetError
  440. )
  441. if not partial_results:
  442. break
  443. results.extend(partial_results)
  444. if len(partial_results) < query["max"]:
  445. break
  446. page += 1
  447. return results
  448. def __fetch_paginated(self, url, query=None):
  449. """Make a specific paginated request.
  450. :param url: The url on which the query is executed
  451. :type url: str
  452. :param query: Pagination settings
  453. :type query: dict
  454. :returns: Response
  455. :rtype: dict
  456. """
  457. query = query or {}
  458. return raise_error_from_response(self.connection.raw_get(url, **query), KeycloakGetError)
  459. def get_current_realm(self) -> str:
  460. """Return the currently configured realm.
  461. :returns: Currently configured realm name
  462. :rtype: str
  463. """
  464. return self.connection.realm_name
  465. def change_current_realm(self, realm_name: str) -> None:
  466. """Change the current realm.
  467. :param realm_name: The name of the realm to be configured as current
  468. :type realm_name: str
  469. """
  470. self.connection.realm_name = realm_name
  471. def import_realm(self, payload):
  472. """Import a new realm from a RealmRepresentation.
  473. Realm name must be unique.
  474. RealmRepresentation
  475. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  476. :param payload: RealmRepresentation
  477. :type payload: dict
  478. :return: RealmRepresentation
  479. :rtype: dict
  480. """
  481. data_raw = self.connection.raw_post(
  482. urls_patterns.URL_ADMIN_REALMS, data=json.dumps(payload)
  483. )
  484. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  485. def partial_import_realm(self, realm_name, payload):
  486. """Partial import realm configuration from PartialImportRepresentation.
  487. Realm partialImport is used for modifying configuration of existing realm.
  488. PartialImportRepresentation
  489. https://www.keycloak.org/docs-api/18.0/rest-api/#_partialimportrepresentation
  490. :param realm_name: Realm name (not the realm id)
  491. :type realm_name: str
  492. :param payload: PartialImportRepresentation
  493. :type payload: dict
  494. :return: PartialImportResponse
  495. :rtype: dict
  496. """
  497. params_path = {"realm-name": realm_name}
  498. data_raw = self.connection.raw_post(
  499. urls_patterns.URL_ADMIN_REALM_PARTIAL_IMPORT.format(**params_path),
  500. data=json.dumps(payload),
  501. )
  502. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[200])
  503. def export_realm(self, export_clients=False, export_groups_and_role=False):
  504. """Export the realm configurations in the json format.
  505. RealmRepresentation
  506. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_partialexport
  507. :param export_clients: Skip if not want to export realm clients
  508. :type export_clients: bool
  509. :param export_groups_and_role: Skip if not want to export realm groups and roles
  510. :type export_groups_and_role: bool
  511. :return: realm configurations JSON
  512. :rtype: dict
  513. """
  514. params_path = {
  515. "realm-name": self.connection.realm_name,
  516. "export-clients": export_clients,
  517. "export-groups-and-roles": export_groups_and_role,
  518. }
  519. data_raw = self.connection.raw_post(
  520. urls_patterns.URL_ADMIN_REALM_EXPORT.format(**params_path), data=""
  521. )
  522. return raise_error_from_response(data_raw, KeycloakPostError)
  523. def get_realms(self):
  524. """List all realms in Keycloak deployment.
  525. :return: realms list
  526. :rtype: list
  527. """
  528. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_REALMS)
  529. return raise_error_from_response(data_raw, KeycloakGetError)
  530. def get_realm(self, realm_name):
  531. """Get a specific realm.
  532. RealmRepresentation:
  533. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  534. :param realm_name: Realm name (not the realm id)
  535. :type realm_name: str
  536. :return: RealmRepresentation
  537. :rtype: dict
  538. """
  539. params_path = {"realm-name": realm_name}
  540. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_REALM.format(**params_path))
  541. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  542. def create_realm(self, payload, skip_exists=False):
  543. """Create a realm.
  544. RealmRepresentation:
  545. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  546. :param payload: RealmRepresentation
  547. :type payload: dict
  548. :param skip_exists: Skip if Realm already exist.
  549. :type skip_exists: bool
  550. :return: Keycloak server response (RealmRepresentation)
  551. :rtype: dict
  552. """
  553. data_raw = self.connection.raw_post(
  554. urls_patterns.URL_ADMIN_REALMS, data=json.dumps(payload)
  555. )
  556. return raise_error_from_response(
  557. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  558. )
  559. def update_realm(self, realm_name, payload):
  560. """Update a realm.
  561. This will only update top level attributes and will ignore any user,
  562. role, or client information in the payload.
  563. RealmRepresentation:
  564. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  565. :param realm_name: Realm name (not the realm id)
  566. :type realm_name: str
  567. :param payload: RealmRepresentation
  568. :type payload: dict
  569. :return: Http response
  570. :rtype: dict
  571. """
  572. params_path = {"realm-name": realm_name}
  573. data_raw = self.connection.raw_put(
  574. urls_patterns.URL_ADMIN_REALM.format(**params_path), data=json.dumps(payload)
  575. )
  576. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  577. def delete_realm(self, realm_name):
  578. """Delete a realm.
  579. :param realm_name: Realm name (not the realm id)
  580. :type realm_name: str
  581. :return: Http response
  582. :rtype: dict
  583. """
  584. params_path = {"realm-name": realm_name}
  585. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_REALM.format(**params_path))
  586. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  587. def get_users(self, query=None):
  588. """Get all users.
  589. Return a list of users, filtered according to query parameters
  590. UserRepresentation
  591. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  592. :param query: Query parameters (optional)
  593. :type query: dict
  594. :return: users list
  595. :rtype: list
  596. """
  597. query = query or {}
  598. params_path = {"realm-name": self.connection.realm_name}
  599. url = urls_patterns.URL_ADMIN_USERS.format(**params_path)
  600. if "first" in query or "max" in query:
  601. return self.__fetch_paginated(url, query)
  602. return self.__fetch_all(url, query)
  603. def create_idp(self, payload):
  604. """Create an ID Provider.
  605. IdentityProviderRepresentation
  606. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation
  607. :param: payload: IdentityProviderRepresentation
  608. :type payload: dict
  609. :returns: Keycloak server response
  610. :rtype: dict
  611. """
  612. params_path = {"realm-name": self.connection.realm_name}
  613. data_raw = self.connection.raw_post(
  614. urls_patterns.URL_ADMIN_IDPS.format(**params_path), data=json.dumps(payload)
  615. )
  616. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  617. def update_idp(self, idp_alias, payload):
  618. """Update an ID Provider.
  619. IdentityProviderRepresentation
  620. https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_identity_providers_resource
  621. :param: idp_alias: alias for IdP to update
  622. :type idp_alias: str
  623. :param: payload: The IdentityProviderRepresentation
  624. :type payload: dict
  625. :returns: Keycloak server response
  626. :rtype: dict
  627. """
  628. params_path = {"realm-name": self.connection.realm_name, "alias": idp_alias}
  629. data_raw = self.connection.raw_put(
  630. urls_patterns.URL_ADMIN_IDP.format(**params_path), data=json.dumps(payload)
  631. )
  632. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  633. def add_mapper_to_idp(self, idp_alias, payload):
  634. """Create an ID Provider.
  635. IdentityProviderRepresentation
  636. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityprovidermapperrepresentation
  637. :param: idp_alias: alias for Idp to add mapper in
  638. :type idp_alias: str
  639. :param: payload: IdentityProviderMapperRepresentation
  640. :type payload: dict
  641. :returns: Keycloak server response
  642. :rtype: dict
  643. """
  644. params_path = {"realm-name": self.connection.realm_name, "idp-alias": idp_alias}
  645. data_raw = self.connection.raw_post(
  646. urls_patterns.URL_ADMIN_IDP_MAPPERS.format(**params_path), data=json.dumps(payload)
  647. )
  648. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  649. def update_mapper_in_idp(self, idp_alias, mapper_id, payload):
  650. """Update an IdP mapper.
  651. IdentityProviderMapperRepresentation
  652. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_update
  653. :param: idp_alias: alias for Idp to fetch mappers
  654. :type idp_alias: str
  655. :param: mapper_id: Mapper Id to update
  656. :type mapper_id: str
  657. :param: payload: IdentityProviderMapperRepresentation
  658. :type payload: dict
  659. :return: Http response
  660. :rtype: dict
  661. """
  662. params_path = {
  663. "realm-name": self.connection.realm_name,
  664. "idp-alias": idp_alias,
  665. "mapper-id": mapper_id,
  666. }
  667. data_raw = self.connection.raw_put(
  668. urls_patterns.URL_ADMIN_IDP_MAPPER_UPDATE.format(**params_path),
  669. data=json.dumps(payload),
  670. )
  671. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  672. def get_idp_mappers(self, idp_alias):
  673. """Get IDP mappers.
  674. Returns a list of ID Providers mappers
  675. IdentityProviderMapperRepresentation
  676. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getmappers
  677. :param: idp_alias: alias for Idp to fetch mappers
  678. :type idp_alias: str
  679. :return: array IdentityProviderMapperRepresentation
  680. :rtype: list
  681. """
  682. params_path = {"realm-name": self.connection.realm_name, "idp-alias": idp_alias}
  683. data_raw = self.connection.raw_get(
  684. urls_patterns.URL_ADMIN_IDP_MAPPERS.format(**params_path)
  685. )
  686. return raise_error_from_response(data_raw, KeycloakGetError)
  687. def get_idps(self):
  688. """Get IDPs.
  689. Returns a list of ID Providers,
  690. IdentityProviderRepresentation
  691. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation
  692. :return: array IdentityProviderRepresentation
  693. :rtype: list
  694. """
  695. params_path = {"realm-name": self.connection.realm_name}
  696. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_IDPS.format(**params_path))
  697. return raise_error_from_response(data_raw, KeycloakGetError)
  698. def get_idp(self, idp_alias):
  699. """Get IDP provider.
  700. Get the representation of a specific IDP Provider.
  701. IdentityProviderRepresentation
  702. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation
  703. :param: idp_alias: alias for IdP to get
  704. :type idp_alias: str
  705. :return: IdentityProviderRepresentation
  706. :rtype: dict
  707. """
  708. params_path = {"realm-name": self.connection.realm_name, "alias": idp_alias}
  709. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_IDP.format(**params_path))
  710. return raise_error_from_response(data_raw, KeycloakGetError)
  711. def delete_idp(self, idp_alias):
  712. """Delete an ID Provider.
  713. :param: idp_alias: idp alias name
  714. :type idp_alias: str
  715. :returns: Keycloak server response
  716. :rtype: dict
  717. """
  718. params_path = {"realm-name": self.connection.realm_name, "alias": idp_alias}
  719. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_IDP.format(**params_path))
  720. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  721. def create_user(self, payload, exist_ok=False):
  722. """Create a new user.
  723. Username must be unique
  724. UserRepresentation
  725. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  726. :param payload: UserRepresentation
  727. :type payload: dict
  728. :param exist_ok: If False, raise KeycloakGetError if username already exists.
  729. Otherwise, return existing user ID.
  730. :type exist_ok: bool
  731. :return: UserRepresentation
  732. :rtype: dict
  733. """
  734. params_path = {"realm-name": self.connection.realm_name}
  735. if exist_ok:
  736. exists = self.get_user_id(username=payload["username"])
  737. if exists is not None:
  738. return str(exists)
  739. data_raw = self.connection.raw_post(
  740. urls_patterns.URL_ADMIN_USERS.format(**params_path), data=json.dumps(payload)
  741. )
  742. raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  743. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  744. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  745. def users_count(self, query=None):
  746. """Count users.
  747. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_users_resource
  748. :param query: (dict) Query parameters for users count
  749. :type query: dict
  750. :return: counter
  751. :rtype: int
  752. """
  753. query = query or dict()
  754. params_path = {"realm-name": self.connection.realm_name}
  755. data_raw = self.connection.raw_get(
  756. urls_patterns.URL_ADMIN_USERS_COUNT.format(**params_path), **query
  757. )
  758. return raise_error_from_response(data_raw, KeycloakGetError)
  759. def get_user_id(self, username):
  760. """Get internal keycloak user id from username.
  761. This is required for further actions against this user.
  762. UserRepresentation
  763. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  764. :param username: id in UserRepresentation
  765. :type username: str
  766. :return: user_id
  767. :rtype: str
  768. """
  769. lower_user_name = username.lower()
  770. users = self.get_users(query={"username": lower_user_name, "max": 1, "exact": True})
  771. return users[0]["id"] if len(users) == 1 else None
  772. def get_user(self, user_id):
  773. """Get representation of the user.
  774. UserRepresentation
  775. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  776. :param user_id: User id
  777. :type user_id: str
  778. :return: UserRepresentation
  779. """
  780. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  781. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_USER.format(**params_path))
  782. return raise_error_from_response(data_raw, KeycloakGetError)
  783. def get_user_groups(self, user_id, query=None, brief_representation=True):
  784. """Get user groups.
  785. Returns a list of groups of which the user is a member
  786. :param user_id: User id
  787. :type user_id: str
  788. :param query: Additional query options
  789. :type query: dict
  790. :param brief_representation: whether to omit attributes in the response
  791. :type brief_representation: bool
  792. :return: user groups list
  793. :rtype: list
  794. """
  795. query = query or {}
  796. params = {"briefRepresentation": brief_representation}
  797. query.update(params)
  798. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  799. url = urls_patterns.URL_ADMIN_USER_GROUPS.format(**params_path)
  800. if "first" in query or "max" in query:
  801. return self.__fetch_paginated(url, query)
  802. return self.__fetch_all(url, query)
  803. def update_user(self, user_id, payload):
  804. """Update the user.
  805. :param user_id: User id
  806. :type user_id: str
  807. :param payload: UserRepresentation
  808. :type payload: dict
  809. :return: Http response
  810. :rtype: bytes
  811. """
  812. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  813. data_raw = self.connection.raw_put(
  814. urls_patterns.URL_ADMIN_USER.format(**params_path), data=json.dumps(payload)
  815. )
  816. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  817. def disable_user(self, user_id):
  818. """Disable the user from the realm. Disabled users can not log in.
  819. :param user_id: User id
  820. :type user_id: str
  821. :return: Http response
  822. :rtype: bytes
  823. """
  824. return self.update_user(user_id=user_id, payload={"enabled": False})
  825. def enable_user(self, user_id):
  826. """Enable the user from the realm.
  827. :param user_id: User id
  828. :type user_id: str
  829. :return: Http response
  830. :rtype: bytes
  831. """
  832. return self.update_user(user_id=user_id, payload={"enabled": True})
  833. def disable_all_users(self):
  834. """Disable all existing users."""
  835. users = self.get_users()
  836. for user in users:
  837. user_id = user["id"]
  838. self.disable_user(user_id=user_id)
  839. def enable_all_users(self):
  840. """Disable all existing users."""
  841. users = self.get_users()
  842. for user in users:
  843. user_id = user["id"]
  844. self.enable_user(user_id=user_id)
  845. def delete_user(self, user_id):
  846. """Delete the user.
  847. :param user_id: User id
  848. :type user_id: str
  849. :return: Http response
  850. :rtype: bytes
  851. """
  852. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  853. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_USER.format(**params_path))
  854. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  855. def set_user_password(self, user_id, password, temporary=True):
  856. """Set up a password for the user.
  857. If temporary is True, the user will have to reset
  858. the temporary password next time they log in.
  859. https://www.keycloak.org/docs-api/18.0/rest-api/#_users_resource
  860. https://www.keycloak.org/docs-api/18.0/rest-api/#_credentialrepresentation
  861. :param user_id: User id
  862. :type user_id: str
  863. :param password: New password
  864. :type password: str
  865. :param temporary: True if password is temporary
  866. :type temporary: bool
  867. :returns: Response
  868. :rtype: dict
  869. """
  870. payload = {"type": "password", "temporary": temporary, "value": password}
  871. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  872. data_raw = self.connection.raw_put(
  873. urls_patterns.URL_ADMIN_RESET_PASSWORD.format(**params_path), data=json.dumps(payload)
  874. )
  875. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  876. def get_credentials(self, user_id):
  877. """Get user credentials.
  878. Returns a list of credential belonging to the user.
  879. CredentialRepresentation
  880. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation
  881. :param: user_id: user id
  882. :type user_id: str
  883. :returns: Keycloak server response (CredentialRepresentation)
  884. :rtype: dict
  885. """
  886. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  887. data_raw = self.connection.raw_get(
  888. urls_patterns.URL_ADMIN_USER_CREDENTIALS.format(**params_path)
  889. )
  890. return raise_error_from_response(data_raw, KeycloakGetError)
  891. def delete_credential(self, user_id, credential_id):
  892. """Delete credential of the user.
  893. CredentialRepresentation
  894. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation
  895. :param: user_id: user id
  896. :type user_id: str
  897. :param: credential_id: credential id
  898. :type credential_id: str
  899. :return: Keycloak server response (ClientRepresentation)
  900. :rtype: bytes
  901. """
  902. params_path = {
  903. "realm-name": self.connection.realm_name,
  904. "id": user_id,
  905. "credential_id": credential_id,
  906. }
  907. data_raw = self.connection.raw_delete(
  908. urls_patterns.URL_ADMIN_USER_CREDENTIAL.format(**params_path)
  909. )
  910. return raise_error_from_response(data_raw, KeycloakDeleteError)
  911. def user_logout(self, user_id):
  912. """Log out the user.
  913. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_logout
  914. :param user_id: User id
  915. :type user_id: str
  916. :returns: Keycloak server response
  917. :rtype: bytes
  918. """
  919. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  920. data_raw = self.connection.raw_post(
  921. urls_patterns.URL_ADMIN_USER_LOGOUT.format(**params_path), data=""
  922. )
  923. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  924. def user_consents(self, user_id):
  925. """Get consents granted by the user.
  926. UserConsentRepresentation
  927. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userconsentrepresentation
  928. :param user_id: User id
  929. :type user_id: str
  930. :returns: List of UserConsentRepresentations
  931. :rtype: list
  932. """
  933. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  934. data_raw = self.connection.raw_get(
  935. urls_patterns.URL_ADMIN_USER_CONSENTS.format(**params_path)
  936. )
  937. return raise_error_from_response(data_raw, KeycloakGetError)
  938. def get_user_social_logins(self, user_id):
  939. """Get user social logins.
  940. Returns a list of federated identities/social logins of which the user has been associated
  941. with
  942. :param user_id: User id
  943. :type user_id: str
  944. :returns: Federated identities list
  945. :rtype: list
  946. """
  947. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  948. data_raw = self.connection.raw_get(
  949. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path)
  950. )
  951. return raise_error_from_response(data_raw, KeycloakGetError)
  952. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  953. """Add a federated identity / social login provider to the user.
  954. :param user_id: User id
  955. :type user_id: str
  956. :param provider_id: Social login provider id
  957. :type provider_id: str
  958. :param provider_userid: userid specified by the provider
  959. :type provider_userid: str
  960. :param provider_username: username specified by the provider
  961. :type provider_username: str
  962. :returns: Keycloak server response
  963. :rtype: bytes
  964. """
  965. payload = {
  966. "identityProvider": provider_id,
  967. "userId": provider_userid,
  968. "userName": provider_username,
  969. }
  970. params_path = {
  971. "realm-name": self.connection.realm_name,
  972. "id": user_id,
  973. "provider": provider_id,
  974. }
  975. data_raw = self.connection.raw_post(
  976. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path),
  977. data=json.dumps(payload),
  978. )
  979. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201, 204])
  980. def delete_user_social_login(self, user_id, provider_id):
  981. """Delete a federated identity / social login provider from the user.
  982. :param user_id: User id
  983. :type user_id: str
  984. :param provider_id: Social login provider id
  985. :type provider_id: str
  986. :returns: Keycloak server response
  987. :rtype: bytes
  988. """
  989. params_path = {
  990. "realm-name": self.connection.realm_name,
  991. "id": user_id,
  992. "provider": provider_id,
  993. }
  994. data_raw = self.connection.raw_delete(
  995. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path)
  996. )
  997. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  998. def send_update_account(
  999. self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None
  1000. ):
  1001. """Send an update account email to the user.
  1002. An email contains a link the user can click to perform a set of required actions.
  1003. :param user_id: User id
  1004. :type user_id: str
  1005. :param payload: A list of actions for the user to complete
  1006. :type payload: list
  1007. :param client_id: Client id (optional)
  1008. :type client_id: str
  1009. :param lifespan: Number of seconds after which the generated token expires (optional)
  1010. :type lifespan: int
  1011. :param redirect_uri: The redirect uri (optional)
  1012. :type redirect_uri: str
  1013. :returns: Keycloak server response
  1014. :rtype: bytes
  1015. """
  1016. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  1017. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  1018. data_raw = self.connection.raw_put(
  1019. urls_patterns.URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  1020. data=json.dumps(payload),
  1021. **params_query,
  1022. )
  1023. return raise_error_from_response(data_raw, KeycloakPutError)
  1024. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  1025. """Send a update account email to the user.
  1026. An email contains a link the user can click to perform a set of required actions.
  1027. :param user_id: User id
  1028. :type user_id: str
  1029. :param client_id: Client id (optional)
  1030. :type client_id: str
  1031. :param redirect_uri: Redirect uri (optional)
  1032. :type redirect_uri: str
  1033. :returns: Keycloak server response
  1034. :rtype: bytes
  1035. """
  1036. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  1037. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  1038. data_raw = self.connection.raw_put(
  1039. urls_patterns.URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  1040. data={},
  1041. **params_query,
  1042. )
  1043. return raise_error_from_response(data_raw, KeycloakPutError)
  1044. def get_sessions(self, user_id):
  1045. """Get sessions associated with the user.
  1046. UserSessionRepresentation
  1047. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation
  1048. :param user_id: Id of user
  1049. :type user_id: str
  1050. :return: UserSessionRepresentation
  1051. :rtype: dict
  1052. """
  1053. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  1054. data_raw = self.connection.raw_get(
  1055. urls_patterns.URL_ADMIN_GET_SESSIONS.format(**params_path)
  1056. )
  1057. return raise_error_from_response(data_raw, KeycloakGetError)
  1058. def get_server_info(self):
  1059. """Get themes, social providers, etc. on this server.
  1060. ServerInfoRepresentation
  1061. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation
  1062. :return: ServerInfoRepresentation
  1063. :rtype: dict
  1064. """
  1065. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_SERVER_INFO)
  1066. return raise_error_from_response(data_raw, KeycloakGetError)
  1067. def get_groups(self, query=None):
  1068. """Get groups.
  1069. Returns a list of groups belonging to the realm
  1070. GroupRepresentation
  1071. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1072. :param query: Additional query options
  1073. :type query: dict
  1074. :return: array GroupRepresentation
  1075. :rtype: list
  1076. """
  1077. query = query or {}
  1078. params_path = {"realm-name": self.connection.realm_name}
  1079. url = urls_patterns.URL_ADMIN_GROUPS.format(**params_path)
  1080. if "first" in query or "max" in query:
  1081. groups = self.__fetch_paginated(url, query)
  1082. else:
  1083. groups = self.__fetch_all(url, query)
  1084. # For version +23.0.0
  1085. for group in groups:
  1086. if group.get("subGroupCount"):
  1087. group["subGroups"] = self.get_group_children(group.get("id"))
  1088. return groups
  1089. def get_group(self, group_id):
  1090. """Get group by id.
  1091. Returns full group details
  1092. GroupRepresentation
  1093. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1094. :param group_id: The group id
  1095. :type group_id: str
  1096. :return: Keycloak server response (GroupRepresentation)
  1097. :rtype: dict
  1098. """
  1099. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1100. response = self.connection.raw_get(urls_patterns.URL_ADMIN_GROUP.format(**params_path))
  1101. if response.status_code >= 400:
  1102. return raise_error_from_response(response, KeycloakGetError)
  1103. # For version +23.0.0
  1104. group = response.json()
  1105. if group.get("subGroupCount"):
  1106. group["subGroups"] = self.get_group_children(group.get("id"))
  1107. return group
  1108. def get_subgroups(self, group, path):
  1109. """Get subgroups.
  1110. Utility function to iterate through nested group structures
  1111. GroupRepresentation
  1112. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1113. :param group: group (GroupRepresentation)
  1114. :type group: dict
  1115. :param path: group path (string)
  1116. :type path: str
  1117. :return: Keycloak server response (GroupRepresentation)
  1118. :rtype: dict
  1119. """
  1120. for subgroup in group["subGroups"]:
  1121. if subgroup["path"] == path:
  1122. return subgroup
  1123. elif subgroup["subGroups"]:
  1124. for subgroup in group["subGroups"]:
  1125. result = self.get_subgroups(subgroup, path)
  1126. if result:
  1127. return result
  1128. # went through the tree without hits
  1129. return None
  1130. def get_group_children(self, group_id):
  1131. """Get group children by id.
  1132. Returns full group children details
  1133. :param group_id: The group id
  1134. :type group_id: str
  1135. :return: Keycloak server response (GroupRepresentation)
  1136. :rtype: dict
  1137. """
  1138. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1139. data_raw = self.connection.raw_get(
  1140. urls_patterns.URL_ADMIN_GROUP_CHILD.format(**params_path)
  1141. )
  1142. return raise_error_from_response(data_raw, KeycloakGetError)
  1143. def get_group_members(self, group_id, query=None):
  1144. """Get members by group id.
  1145. Returns group members
  1146. GroupRepresentation
  1147. https://www.keycloak.org/docs-api/18.0/rest-api/#_userrepresentation
  1148. :param group_id: The group id
  1149. :type group_id: str
  1150. :param query: Additional query parameters
  1151. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getmembers)
  1152. :type query: dict
  1153. :return: Keycloak server response (UserRepresentation)
  1154. :rtype: list
  1155. """
  1156. query = query or {}
  1157. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1158. url = urls_patterns.URL_ADMIN_GROUP_MEMBERS.format(**params_path)
  1159. if "first" in query or "max" in query:
  1160. return self.__fetch_paginated(url, query)
  1161. return self.__fetch_all(url, query)
  1162. def get_group_by_path(self, path):
  1163. """Get group id based on name or path.
  1164. Returns full group details for a group defined by path
  1165. GroupRepresentation
  1166. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1167. :param path: group path
  1168. :type path: str
  1169. :return: Keycloak server response (GroupRepresentation)
  1170. :rtype: dict
  1171. """
  1172. params_path = {"realm-name": self.connection.realm_name, "path": path}
  1173. data_raw = self.connection.raw_get(
  1174. urls_patterns.URL_ADMIN_GROUP_BY_PATH.format(**params_path)
  1175. )
  1176. return raise_error_from_response(data_raw, KeycloakGetError)
  1177. def create_group(self, payload, parent=None, skip_exists=False):
  1178. """Create a group in the Realm.
  1179. GroupRepresentation
  1180. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1181. :param payload: GroupRepresentation
  1182. :type payload: dict
  1183. :param parent: parent group's id. Required to create a sub-group.
  1184. :type parent: str
  1185. :param skip_exists: If true then do not raise an error if it already exists
  1186. :type skip_exists: bool
  1187. :return: Group id for newly created group or None for an existing group
  1188. :rtype: str
  1189. """
  1190. if parent is None:
  1191. params_path = {"realm-name": self.connection.realm_name}
  1192. data_raw = self.connection.raw_post(
  1193. urls_patterns.URL_ADMIN_GROUPS.format(**params_path), data=json.dumps(payload)
  1194. )
  1195. else:
  1196. params_path = {"realm-name": self.connection.realm_name, "id": parent}
  1197. data_raw = self.connection.raw_post(
  1198. urls_patterns.URL_ADMIN_GROUP_CHILD.format(**params_path), data=json.dumps(payload)
  1199. )
  1200. raise_error_from_response(
  1201. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1202. )
  1203. try:
  1204. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  1205. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  1206. except KeyError:
  1207. return
  1208. def update_group(self, group_id, payload):
  1209. """Update group, ignores subgroups.
  1210. GroupRepresentation
  1211. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  1212. :param group_id: id of group
  1213. :type group_id: str
  1214. :param payload: GroupRepresentation with updated information.
  1215. :type payload: dict
  1216. :return: Http response
  1217. :rtype: bytes
  1218. """
  1219. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1220. data_raw = self.connection.raw_put(
  1221. urls_patterns.URL_ADMIN_GROUP.format(**params_path), data=json.dumps(payload)
  1222. )
  1223. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1224. def group_set_permissions(self, group_id, enabled=True):
  1225. """Enable/Disable permissions for a group.
  1226. Cannot delete group if disabled
  1227. :param group_id: id of group
  1228. :type group_id: str
  1229. :param enabled: Enabled flag
  1230. :type enabled: bool
  1231. :return: Keycloak server response
  1232. :rtype: bytes
  1233. """
  1234. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1235. data_raw = self.connection.raw_put(
  1236. urls_patterns.URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  1237. data=json.dumps({"enabled": enabled}),
  1238. )
  1239. return raise_error_from_response(data_raw, KeycloakPutError)
  1240. def group_user_add(self, user_id, group_id):
  1241. """Add user to group (user_id and group_id).
  1242. :param user_id: id of user
  1243. :type user_id: str
  1244. :param group_id: id of group to add to
  1245. :type group_id: str
  1246. :return: Keycloak server response
  1247. :rtype: bytes
  1248. """
  1249. params_path = {
  1250. "realm-name": self.connection.realm_name,
  1251. "id": user_id,
  1252. "group-id": group_id,
  1253. }
  1254. data_raw = self.connection.raw_put(
  1255. urls_patterns.URL_ADMIN_USER_GROUP.format(**params_path), data=None
  1256. )
  1257. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1258. def group_user_remove(self, user_id, group_id):
  1259. """Remove user from group (user_id and group_id).
  1260. :param user_id: id of user
  1261. :type user_id: str
  1262. :param group_id: id of group to remove from
  1263. :type group_id: str
  1264. :return: Keycloak server response
  1265. :rtype: bytes
  1266. """
  1267. params_path = {
  1268. "realm-name": self.connection.realm_name,
  1269. "id": user_id,
  1270. "group-id": group_id,
  1271. }
  1272. data_raw = self.connection.raw_delete(
  1273. urls_patterns.URL_ADMIN_USER_GROUP.format(**params_path)
  1274. )
  1275. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1276. def delete_group(self, group_id):
  1277. """Delete a group in the Realm.
  1278. :param group_id: id of group to delete
  1279. :type group_id: str
  1280. :return: Keycloak server response
  1281. :rtype: bytes
  1282. """
  1283. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  1284. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_GROUP.format(**params_path))
  1285. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1286. def get_clients(self):
  1287. """Get clients.
  1288. Returns a list of clients belonging to the realm
  1289. ClientRepresentation
  1290. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1291. :return: Keycloak server response (ClientRepresentation)
  1292. :rtype: list
  1293. """
  1294. params_path = {"realm-name": self.connection.realm_name}
  1295. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_CLIENTS.format(**params_path))
  1296. return raise_error_from_response(data_raw, KeycloakGetError)
  1297. def get_client(self, client_id):
  1298. """Get representation of the client.
  1299. ClientRepresentation
  1300. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1301. :param client_id: id of client (not client-id)
  1302. :type client_id: str
  1303. :return: Keycloak server response (ClientRepresentation)
  1304. :rtype: dict
  1305. """
  1306. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1307. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_CLIENT.format(**params_path))
  1308. return raise_error_from_response(data_raw, KeycloakGetError)
  1309. def get_client_id(self, client_id):
  1310. """Get internal keycloak client id from client-id.
  1311. This is required for further actions against this client.
  1312. :param client_id: clientId in ClientRepresentation
  1313. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1314. :type client_id: str
  1315. :return: client_id (uuid as string)
  1316. :rtype: str
  1317. """
  1318. clients = self.get_clients()
  1319. for client in clients:
  1320. if client_id == client.get("clientId"):
  1321. return client["id"]
  1322. return None
  1323. def get_client_authz_settings(self, client_id):
  1324. """Get authorization json from client.
  1325. :param client_id: id in ClientRepresentation
  1326. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1327. :type client_id: str
  1328. :return: Keycloak server response
  1329. :rtype: dict
  1330. """
  1331. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1332. data_raw = self.connection.raw_get(
  1333. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path)
  1334. )
  1335. return raise_error_from_response(data_raw, KeycloakGetError)
  1336. def create_client_authz_resource(self, client_id, payload, skip_exists=False):
  1337. """Create resources of client.
  1338. :param client_id: id in ClientRepresentation
  1339. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1340. :type client_id: str
  1341. :param payload: ResourceRepresentation
  1342. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  1343. :type payload: dict
  1344. :param skip_exists: Skip the creation in case the resource exists
  1345. :type skip_exists: bool
  1346. :return: Keycloak server response
  1347. :rtype: bytes
  1348. """
  1349. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1350. data_raw = self.connection.raw_post(
  1351. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path),
  1352. data=json.dumps(payload),
  1353. )
  1354. return raise_error_from_response(
  1355. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1356. )
  1357. def update_client_authz_resource(self, client_id, resource_id, payload):
  1358. """Update resource of client.
  1359. Any parameter missing from the ResourceRepresentation in the payload WILL be set
  1360. to default by the Keycloak server.
  1361. :param client_id: id in ClientRepresentation
  1362. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1363. :type client_id: str
  1364. :param payload: ResourceRepresentation
  1365. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  1366. :type payload: dict
  1367. :param client_id: id in ClientRepresentation
  1368. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1369. :type client_id: str
  1370. :param resource_id: id in ResourceRepresentation
  1371. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  1372. :type resource_id: str
  1373. :return: Keycloak server response
  1374. :rtype: bytes
  1375. """
  1376. params_path = {
  1377. "realm-name": self.connection.realm_name,
  1378. "id": client_id,
  1379. "resource-id": resource_id,
  1380. }
  1381. data_raw = self.connection.raw_put(
  1382. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCE.format(**params_path),
  1383. data=json.dumps(payload),
  1384. )
  1385. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1386. def delete_client_authz_resource(self, client_id: str, resource_id: str):
  1387. """Delete a client resource.
  1388. :param client_id: id in ClientRepresentation
  1389. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1390. :type client_id: str
  1391. :param resource_id: id in ResourceRepresentation
  1392. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  1393. :type resource_id: str
  1394. :return: Keycloak server response
  1395. :rtype: bytes
  1396. """
  1397. params_path = {
  1398. "realm-name": self.connection.realm_name,
  1399. "id": client_id,
  1400. "resource-id": resource_id,
  1401. }
  1402. data_raw = self.connection.raw_delete(
  1403. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCE.format(**params_path)
  1404. )
  1405. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1406. def get_client_authz_resources(self, client_id):
  1407. """Get resources from client.
  1408. :param client_id: id in ClientRepresentation
  1409. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1410. :type client_id: str
  1411. :return: Keycloak server response (ResourceRepresentation)
  1412. :rtype: list
  1413. """
  1414. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1415. data_raw = self.connection.raw_get(
  1416. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path)
  1417. )
  1418. return raise_error_from_response(data_raw, KeycloakGetError)
  1419. def get_client_authz_resource(self, client_id: str, resource_id: str):
  1420. """Get a client resource.
  1421. :param client_id: id in ClientRepresentation
  1422. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1423. :type client_id: str
  1424. :param resource_id: id in ResourceRepresentation
  1425. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  1426. :type resource_id: str
  1427. :return: Keycloak server response (ResourceRepresentation)
  1428. :rtype: dict
  1429. """
  1430. params_path = {
  1431. "realm-name": self.connection.realm_name,
  1432. "id": client_id,
  1433. "resource-id": resource_id,
  1434. }
  1435. data_raw = self.connection.raw_get(
  1436. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCE.format(**params_path)
  1437. )
  1438. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  1439. def create_client_authz_role_based_policy(self, client_id, payload, skip_exists=False):
  1440. """Create role-based policy of client.
  1441. Payload example::
  1442. payload={
  1443. "type": "role",
  1444. "logic": "POSITIVE",
  1445. "decisionStrategy": "UNANIMOUS",
  1446. "name": "Policy-1",
  1447. "roles": [
  1448. {
  1449. "id": id
  1450. }
  1451. ]
  1452. }
  1453. :param client_id: id in ClientRepresentation
  1454. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1455. :type client_id: str
  1456. :param payload: No Document
  1457. :type payload: dict
  1458. :param skip_exists: Skip creation in case the object exists
  1459. :type skip_exists: bool
  1460. :return: Keycloak server response
  1461. :rtype: bytes
  1462. """
  1463. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1464. data_raw = self.connection.raw_post(
  1465. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_POLICY.format(**params_path),
  1466. data=json.dumps(payload),
  1467. )
  1468. return raise_error_from_response(
  1469. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1470. )
  1471. def create_client_authz_policy(self, client_id, payload, skip_exists=False):
  1472. """Create an authz policy of client.
  1473. Payload example::
  1474. payload={
  1475. "name": "Policy-time-based",
  1476. "type": "time",
  1477. "logic": "POSITIVE",
  1478. "decisionStrategy": "UNANIMOUS",
  1479. "config": {
  1480. "hourEnd": "18",
  1481. "hour": "9"
  1482. }
  1483. }
  1484. :param client_id: id in ClientRepresentation
  1485. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1486. :type client_id: str
  1487. :param payload: No Document
  1488. :type payload: dict
  1489. :param skip_exists: Skip creation in case the object exists
  1490. :type skip_exists: bool
  1491. :return: Keycloak server response
  1492. :rtype: bytes
  1493. """
  1494. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1495. data_raw = self.connection.raw_post(
  1496. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICIES.format(**params_path),
  1497. data=json.dumps(payload),
  1498. )
  1499. return raise_error_from_response(
  1500. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1501. )
  1502. def create_client_authz_resource_based_permission(self, client_id, payload, skip_exists=False):
  1503. """Create resource-based permission of client.
  1504. Payload example::
  1505. payload={
  1506. "type": "resource",
  1507. "logic": "POSITIVE",
  1508. "decisionStrategy": "UNANIMOUS",
  1509. "name": "Permission-Name",
  1510. "resources": [
  1511. resource_id
  1512. ],
  1513. "policies": [
  1514. policy_id
  1515. ]
  1516. :param client_id: id in ClientRepresentation
  1517. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1518. :type client_id: str
  1519. :param payload: PolicyRepresentation
  1520. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_policyrepresentation
  1521. :type payload: dict
  1522. :param skip_exists: Skip creation in case the object already exists
  1523. :type skip_exists: bool
  1524. :return: Keycloak server response
  1525. :rtype: bytes
  1526. """
  1527. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1528. data_raw = self.connection.raw_post(
  1529. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCE_BASED_PERMISSION.format(**params_path),
  1530. data=json.dumps(payload),
  1531. )
  1532. return raise_error_from_response(
  1533. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1534. )
  1535. def get_client_authz_scopes(self, client_id):
  1536. """Get scopes from client.
  1537. :param client_id: id in ClientRepresentation
  1538. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1539. :type client_id: str
  1540. :return: Keycloak server response
  1541. :rtype: list
  1542. """
  1543. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1544. data_raw = self.connection.raw_get(
  1545. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SCOPES.format(**params_path)
  1546. )
  1547. return raise_error_from_response(data_raw, KeycloakGetError)
  1548. def create_client_authz_scopes(self, client_id, payload):
  1549. """Create scopes for client.
  1550. :param client_id: id in ClientRepresentation
  1551. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1552. :param payload: ScopeRepresentation
  1553. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_ScopeRepresentation
  1554. :type payload: dict
  1555. :type client_id: str
  1556. :return: Keycloak server response
  1557. :rtype: bytes
  1558. """
  1559. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1560. data_raw = self.connection.raw_post(
  1561. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SCOPES.format(**params_path),
  1562. data=json.dumps(payload),
  1563. )
  1564. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1565. def get_client_authz_permissions(self, client_id):
  1566. """Get permissions from client.
  1567. :param client_id: id in ClientRepresentation
  1568. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1569. :type client_id: str
  1570. :return: Keycloak server response
  1571. :rtype: list
  1572. """
  1573. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1574. data_raw = self.connection.raw_get(
  1575. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_PERMISSIONS.format(**params_path)
  1576. )
  1577. return raise_error_from_response(data_raw, KeycloakGetError)
  1578. def get_client_authz_policies(self, client_id):
  1579. """Get policies from client.
  1580. :param client_id: id in ClientRepresentation
  1581. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1582. :type client_id: str
  1583. :return: Keycloak server response
  1584. :rtype: list
  1585. """
  1586. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1587. data_raw = self.connection.raw_get(
  1588. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICIES.format(**params_path)
  1589. )
  1590. return raise_error_from_response(data_raw, KeycloakGetError)
  1591. def delete_client_authz_policy(self, client_id, policy_id):
  1592. """Delete a policy from client.
  1593. :param client_id: id in ClientRepresentation
  1594. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1595. :type client_id: str
  1596. :param policy_id: id in PolicyRepresentation
  1597. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_policyrepresentation
  1598. :type policy_id: str
  1599. :return: Keycloak server response
  1600. :rtype: dict
  1601. """
  1602. params_path = {
  1603. "realm-name": self.connection.realm_name,
  1604. "id": client_id,
  1605. "policy-id": policy_id,
  1606. }
  1607. data_raw = self.connection.raw_delete(
  1608. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICY.format(**params_path)
  1609. )
  1610. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1611. def get_client_authz_policy(self, client_id, policy_id):
  1612. """Get a policy from client.
  1613. :param client_id: id in ClientRepresentation
  1614. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1615. :type client_id: str
  1616. :param policy_id: id in PolicyRepresentation
  1617. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_policyrepresentation
  1618. :type policy_id: str
  1619. :return: Keycloak server response
  1620. :rtype: dict
  1621. """
  1622. params_path = {
  1623. "realm-name": self.connection.realm_name,
  1624. "id": client_id,
  1625. "policy-id": policy_id,
  1626. }
  1627. data_raw = self.connection.raw_get(
  1628. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICY.format(**params_path)
  1629. )
  1630. return raise_error_from_response(data_raw, KeycloakGetError)
  1631. def get_client_service_account_user(self, client_id):
  1632. """Get service account user from client.
  1633. :param client_id: id in ClientRepresentation
  1634. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1635. :type client_id: str
  1636. :return: UserRepresentation
  1637. :rtype: dict
  1638. """
  1639. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1640. data_raw = self.connection.raw_get(
  1641. urls_patterns.URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path)
  1642. )
  1643. return raise_error_from_response(data_raw, KeycloakGetError)
  1644. def get_client_default_client_scopes(self, client_id):
  1645. """Get all default client scopes from client.
  1646. :param client_id: id of the client in which the new default client scope should be added
  1647. :type client_id: str
  1648. :return: list of client scopes with id and name
  1649. :rtype: list
  1650. """
  1651. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1652. data_raw = self.connection.raw_get(
  1653. urls_patterns.URL_ADMIN_CLIENT_DEFAULT_CLIENT_SCOPES.format(**params_path)
  1654. )
  1655. return raise_error_from_response(data_raw, KeycloakGetError)
  1656. def add_client_default_client_scope(self, client_id, client_scope_id, payload):
  1657. """Add a client scope to the default client scopes from client.
  1658. Payload example::
  1659. payload={
  1660. "realm":"testrealm",
  1661. "client":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
  1662. "clientScopeId":"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
  1663. }
  1664. :param client_id: id of the client in which the new default client scope should be added
  1665. :type client_id: str
  1666. :param client_scope_id: id of the new client scope that should be added
  1667. :type client_scope_id: str
  1668. :param payload: dictionary with realm, client and clientScopeId
  1669. :type payload: dict
  1670. :return: Http response
  1671. :rtype: bytes
  1672. """
  1673. params_path = {
  1674. "realm-name": self.connection.realm_name,
  1675. "id": client_id,
  1676. "client_scope_id": client_scope_id,
  1677. }
  1678. data_raw = self.connection.raw_put(
  1679. urls_patterns.URL_ADMIN_CLIENT_DEFAULT_CLIENT_SCOPE.format(**params_path),
  1680. data=json.dumps(payload),
  1681. )
  1682. return raise_error_from_response(data_raw, KeycloakPutError)
  1683. def delete_client_default_client_scope(self, client_id, client_scope_id):
  1684. """Delete a client scope from the default client scopes of the client.
  1685. :param client_id: id of the client in which the default client scope should be deleted
  1686. :type client_id: str
  1687. :param client_scope_id: id of the client scope that should be deleted
  1688. :type client_scope_id: str
  1689. :return: list of client scopes with id and name
  1690. :rtype: list
  1691. """
  1692. params_path = {
  1693. "realm-name": self.connection.realm_name,
  1694. "id": client_id,
  1695. "client_scope_id": client_scope_id,
  1696. }
  1697. data_raw = self.connection.raw_delete(
  1698. urls_patterns.URL_ADMIN_CLIENT_DEFAULT_CLIENT_SCOPE.format(**params_path)
  1699. )
  1700. return raise_error_from_response(data_raw, KeycloakDeleteError)
  1701. def get_client_optional_client_scopes(self, client_id):
  1702. """Get all optional client scopes from client.
  1703. :param client_id: id of the client in which the new optional client scope should be added
  1704. :type client_id: str
  1705. :return: list of client scopes with id and name
  1706. :rtype: list
  1707. """
  1708. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1709. data_raw = self.connection.raw_get(
  1710. urls_patterns.URL_ADMIN_CLIENT_OPTIONAL_CLIENT_SCOPES.format(**params_path)
  1711. )
  1712. return raise_error_from_response(data_raw, KeycloakGetError)
  1713. def add_client_optional_client_scope(self, client_id, client_scope_id, payload):
  1714. """Add a client scope to the optional client scopes from client.
  1715. Payload example::
  1716. payload={
  1717. "realm":"testrealm",
  1718. "client":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
  1719. "clientScopeId":"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
  1720. }
  1721. :param client_id: id of the client in which the new optional client scope should be added
  1722. :type client_id: str
  1723. :param client_scope_id: id of the new client scope that should be added
  1724. :type client_scope_id: str
  1725. :param payload: dictionary with realm, client and clientScopeId
  1726. :type payload: dict
  1727. :return: Http response
  1728. :rtype: bytes
  1729. """
  1730. params_path = {
  1731. "realm-name": self.connection.realm_name,
  1732. "id": client_id,
  1733. "client_scope_id": client_scope_id,
  1734. }
  1735. data_raw = self.connection.raw_put(
  1736. urls_patterns.URL_ADMIN_CLIENT_OPTIONAL_CLIENT_SCOPE.format(**params_path),
  1737. data=json.dumps(payload),
  1738. )
  1739. return raise_error_from_response(data_raw, KeycloakPutError)
  1740. def delete_client_optional_client_scope(self, client_id, client_scope_id):
  1741. """Delete a client scope from the optional client scopes of the client.
  1742. :param client_id: id of the client in which the optional client scope should be deleted
  1743. :type client_id: str
  1744. :param client_scope_id: id of the client scope that should be deleted
  1745. :type client_scope_id: str
  1746. :return: list of client scopes with id and name
  1747. :rtype: list
  1748. """
  1749. params_path = {
  1750. "realm-name": self.connection.realm_name,
  1751. "id": client_id,
  1752. "client_scope_id": client_scope_id,
  1753. }
  1754. data_raw = self.connection.raw_delete(
  1755. urls_patterns.URL_ADMIN_CLIENT_OPTIONAL_CLIENT_SCOPE.format(**params_path)
  1756. )
  1757. return raise_error_from_response(data_raw, KeycloakDeleteError)
  1758. def create_initial_access_token(self, count: int = 1, expiration: int = 1):
  1759. """Create an initial access token.
  1760. :param count: Number of clients that can be registered
  1761. :type count: int
  1762. :param expiration: Days until expireation
  1763. :type expiration: int
  1764. :return: initial access token
  1765. :rtype: str
  1766. """
  1767. payload = {"count": count, "expiration": expiration}
  1768. params_path = {"realm-name": self.connection.realm_name}
  1769. data_raw = self.connection.raw_post(
  1770. urls_patterns.URL_ADMIN_CLIENT_INITIAL_ACCESS.format(**params_path),
  1771. data=json.dumps(payload),
  1772. )
  1773. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[200])
  1774. def create_client(self, payload, skip_exists=False):
  1775. """Create a client.
  1776. ClientRepresentation:
  1777. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1778. :param skip_exists: If true then do not raise an error if client already exists
  1779. :type skip_exists: bool
  1780. :param payload: ClientRepresentation
  1781. :type payload: dict
  1782. :return: Client ID
  1783. :rtype: str
  1784. """
  1785. if skip_exists:
  1786. client_id = self.get_client_id(client_id=payload["clientId"])
  1787. if client_id is not None:
  1788. return client_id
  1789. params_path = {"realm-name": self.connection.realm_name}
  1790. data_raw = self.connection.raw_post(
  1791. urls_patterns.URL_ADMIN_CLIENTS.format(**params_path), data=json.dumps(payload)
  1792. )
  1793. raise_error_from_response(
  1794. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1795. )
  1796. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  1797. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  1798. def update_client(self, client_id, payload):
  1799. """Update a client.
  1800. :param client_id: Client id
  1801. :type client_id: str
  1802. :param payload: ClientRepresentation
  1803. :type payload: dict
  1804. :return: Http response
  1805. :rtype: bytes
  1806. """
  1807. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1808. data_raw = self.connection.raw_put(
  1809. urls_patterns.URL_ADMIN_CLIENT.format(**params_path), data=json.dumps(payload)
  1810. )
  1811. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1812. def delete_client(self, client_id):
  1813. """Get representation of the client.
  1814. ClientRepresentation
  1815. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  1816. :param client_id: keycloak client id (not oauth client-id)
  1817. :type client_id: str
  1818. :return: Keycloak server response (ClientRepresentation)
  1819. :rtype: bytes
  1820. """
  1821. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1822. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_CLIENT.format(**params_path))
  1823. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1824. def get_client_installation_provider(self, client_id, provider_id):
  1825. """Get content for given installation provider.
  1826. Related documentation:
  1827. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource
  1828. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  1829. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation
  1830. :param client_id: Client id
  1831. :type client_id: str
  1832. :param provider_id: provider id to specify response format
  1833. :type provider_id: str
  1834. :returns: Installation providers
  1835. :rtype: list
  1836. """
  1837. params_path = {
  1838. "realm-name": self.connection.realm_name,
  1839. "id": client_id,
  1840. "provider-id": provider_id,
  1841. }
  1842. data_raw = self.connection.raw_get(
  1843. urls_patterns.URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path)
  1844. )
  1845. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  1846. def get_realm_roles(self, brief_representation=True, search_text=""):
  1847. """Get all roles for the realm or client.
  1848. RoleRepresentation
  1849. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1850. :param brief_representation: whether to omit role attributes in the response
  1851. :type brief_representation: bool
  1852. :param search_text: optional search text to limit the returned result.
  1853. :type search_text: str
  1854. :return: Keycloak server response (RoleRepresentation)
  1855. :rtype: list
  1856. """
  1857. url = urls_patterns.URL_ADMIN_REALM_ROLES
  1858. params_path = {"realm-name": self.connection.realm_name}
  1859. params = {"briefRepresentation": brief_representation}
  1860. data_raw = self.connection.raw_get(
  1861. urls_patterns.URL_ADMIN_REALM_ROLES.format(**params_path), **params
  1862. )
  1863. # set the search_text path param, if it is a valid string
  1864. if search_text is not None and search_text.strip() != "":
  1865. params_path["search-text"] = search_text
  1866. url = urls_patterns.URL_ADMIN_REALM_ROLES_SEARCH
  1867. data_raw = self.connection.raw_get(url.format(**params_path), **params)
  1868. return raise_error_from_response(data_raw, KeycloakGetError)
  1869. def get_realm_role_groups(self, role_name, query=None, brief_representation=True):
  1870. """Get role groups of realm by role name.
  1871. :param role_name: Name of the role.
  1872. :type role_name: str
  1873. :param query: Additional Query parameters
  1874. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_parameters_226)
  1875. :type query: dict
  1876. :param brief_representation: whether to omit role attributes in the response
  1877. :type brief_representation: bool
  1878. :return: Keycloak Server Response (GroupRepresentation)
  1879. :rtype: list
  1880. """
  1881. query = query or {}
  1882. params = {"briefRepresentation": brief_representation}
  1883. query.update(params)
  1884. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  1885. url = urls_patterns.URL_ADMIN_REALM_ROLES_GROUPS.format(**params_path)
  1886. if "first" in query or "max" in query:
  1887. return self.__fetch_paginated(url, query)
  1888. return self.__fetch_all(url, query)
  1889. def get_realm_role_members(self, role_name, query=None):
  1890. """Get role members of realm by role name.
  1891. :param role_name: Name of the role.
  1892. :type role_name: str
  1893. :param query: Additional Query parameters
  1894. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_roles_resource)
  1895. :type query: dict
  1896. :return: Keycloak Server Response (UserRepresentation)
  1897. :rtype: list
  1898. """
  1899. query = query or dict()
  1900. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  1901. return self.__fetch_all(
  1902. urls_patterns.URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query
  1903. )
  1904. def get_default_realm_role_id(self):
  1905. """Get the ID of the default realm role.
  1906. :return: Realm role ID
  1907. :rtype: str
  1908. """
  1909. all_realm_roles = self.get_realm_roles()
  1910. default_realm_roles = [
  1911. realm_role
  1912. for realm_role in all_realm_roles
  1913. if realm_role["name"] == f"default-roles-{self.connection.realm_name}"
  1914. ]
  1915. return default_realm_roles[0]["id"]
  1916. def get_realm_default_roles(self):
  1917. """Get all the default realm roles.
  1918. :return: Keycloak Server Response (UserRepresentation)
  1919. :rtype: list
  1920. """
  1921. params_path = {
  1922. "realm-name": self.connection.realm_name,
  1923. "role-id": self.get_default_realm_role_id(),
  1924. }
  1925. data_raw = self.connection.raw_get(
  1926. urls_patterns.URL_ADMIN_REALM_ROLE_COMPOSITES_REALM.format(**params_path)
  1927. )
  1928. return raise_error_from_response(data_raw, KeycloakGetError)
  1929. def remove_realm_default_roles(self, payload):
  1930. """Remove a set of default realm roles.
  1931. :param payload: List of RoleRepresentations
  1932. :type payload: list
  1933. :return: Keycloak Server Response
  1934. :rtype: dict
  1935. """
  1936. params_path = {
  1937. "realm-name": self.connection.realm_name,
  1938. "role-id": self.get_default_realm_role_id(),
  1939. }
  1940. data_raw = self.connection.raw_delete(
  1941. urls_patterns.URL_ADMIN_REALM_ROLE_COMPOSITES.format(**params_path),
  1942. data=json.dumps(payload),
  1943. )
  1944. return raise_error_from_response(data_raw, KeycloakDeleteError)
  1945. def add_realm_default_roles(self, payload):
  1946. """Add a set of default realm roles.
  1947. :param payload: List of RoleRepresentations
  1948. :type payload: list
  1949. :return: Keycloak Server Response
  1950. :rtype: dict
  1951. """
  1952. params_path = {
  1953. "realm-name": self.connection.realm_name,
  1954. "role-id": self.get_default_realm_role_id(),
  1955. }
  1956. data_raw = self.connection.raw_post(
  1957. urls_patterns.URL_ADMIN_REALM_ROLE_COMPOSITES.format(**params_path),
  1958. data=json.dumps(payload),
  1959. )
  1960. return raise_error_from_response(data_raw, KeycloakPostError)
  1961. def get_client_roles(self, client_id, brief_representation=True):
  1962. """Get all roles for the client.
  1963. RoleRepresentation
  1964. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1965. :param client_id: id of client (not client-id)
  1966. :type client_id: str
  1967. :param brief_representation: whether to omit role attributes in the response
  1968. :type brief_representation: bool
  1969. :return: Keycloak server response (RoleRepresentation)
  1970. :rtype: list
  1971. """
  1972. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  1973. params = {"briefRepresentation": brief_representation}
  1974. data_raw = self.connection.raw_get(
  1975. urls_patterns.URL_ADMIN_CLIENT_ROLES.format(**params_path), **params
  1976. )
  1977. return raise_error_from_response(data_raw, KeycloakGetError)
  1978. def get_client_role(self, client_id, role_name):
  1979. """Get client role id by name.
  1980. This is required for further actions with this role.
  1981. RoleRepresentation
  1982. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1983. :param client_id: id of client (not client-id)
  1984. :type client_id: str
  1985. :param role_name: role's name (not id!)
  1986. :type role_name: str
  1987. :return: role_id
  1988. :rtype: str
  1989. """
  1990. params_path = {
  1991. "realm-name": self.connection.realm_name,
  1992. "id": client_id,
  1993. "role-name": role_name,
  1994. }
  1995. data_raw = self.connection.raw_get(
  1996. urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path)
  1997. )
  1998. return raise_error_from_response(data_raw, KeycloakGetError)
  1999. def get_client_role_id(self, client_id, role_name):
  2000. """Get client role id by name.
  2001. This is required for further actions with this role.
  2002. RoleRepresentation
  2003. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2004. :param client_id: id of client (not client-id)
  2005. :type client_id: str
  2006. :param role_name: role's name (not id!)
  2007. :type role_name: str
  2008. :return: role_id
  2009. :rtype: str
  2010. """
  2011. role = self.get_client_role(client_id, role_name)
  2012. return role.get("id")
  2013. def create_client_role(self, client_role_id, payload, skip_exists=False):
  2014. """Create a client role.
  2015. RoleRepresentation
  2016. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2017. :param client_role_id: id of client (not client-id)
  2018. :type client_role_id: str
  2019. :param payload: RoleRepresentation
  2020. :type payload: dict
  2021. :param skip_exists: If true then do not raise an error if client role already exists
  2022. :type skip_exists: bool
  2023. :return: Client role name
  2024. :rtype: str
  2025. """
  2026. if skip_exists:
  2027. try:
  2028. res = self.get_client_role(client_id=client_role_id, role_name=payload["name"])
  2029. return res["name"]
  2030. except KeycloakGetError:
  2031. pass
  2032. params_path = {"realm-name": self.connection.realm_name, "id": client_role_id}
  2033. data_raw = self.connection.raw_post(
  2034. urls_patterns.URL_ADMIN_CLIENT_ROLES.format(**params_path), data=json.dumps(payload)
  2035. )
  2036. raise_error_from_response(
  2037. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  2038. )
  2039. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  2040. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  2041. def add_composite_client_roles_to_role(self, client_role_id, role_name, roles):
  2042. """Add composite roles to client role.
  2043. :param client_role_id: id of client (not client-id)
  2044. :type client_role_id: str
  2045. :param role_name: The name of the role
  2046. :type role_name: str
  2047. :param roles: roles list or role (use RoleRepresentation) to be updated
  2048. :type roles: list
  2049. :return: Keycloak server response
  2050. :rtype: bytes
  2051. """
  2052. payload = roles if isinstance(roles, list) else [roles]
  2053. params_path = {
  2054. "realm-name": self.connection.realm_name,
  2055. "id": client_role_id,
  2056. "role-name": role_name,
  2057. }
  2058. data_raw = self.connection.raw_post(
  2059. urls_patterns.URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE.format(**params_path),
  2060. data=json.dumps(payload),
  2061. )
  2062. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2063. def update_client_role(self, client_id, role_name, payload):
  2064. """Update a client role.
  2065. RoleRepresentation
  2066. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2067. :param client_id: id of client (not client-id)
  2068. :type client_id: str
  2069. :param role_name: role's name (not id!)
  2070. :type role_name: str
  2071. :param payload: RoleRepresentation
  2072. :type payload: dict
  2073. :returns: Keycloak server response
  2074. :rtype: bytes
  2075. """
  2076. params_path = {
  2077. "realm-name": self.connection.realm_name,
  2078. "id": client_id,
  2079. "role-name": role_name,
  2080. }
  2081. data_raw = self.connection.raw_put(
  2082. urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path), data=json.dumps(payload)
  2083. )
  2084. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  2085. def delete_client_role(self, client_role_id, role_name):
  2086. """Delete a client role.
  2087. RoleRepresentation
  2088. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2089. :param client_role_id: id of client (not client-id)
  2090. :type client_role_id: str
  2091. :param role_name: role's name (not id!)
  2092. :type role_name: str
  2093. :returns: Keycloak server response
  2094. :rtype: bytes
  2095. """
  2096. params_path = {
  2097. "realm-name": self.connection.realm_name,
  2098. "id": client_role_id,
  2099. "role-name": role_name,
  2100. }
  2101. data_raw = self.connection.raw_delete(
  2102. urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path)
  2103. )
  2104. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2105. def assign_client_role(self, user_id, client_id, roles):
  2106. """Assign a client role to a user.
  2107. :param user_id: id of user
  2108. :type user_id: str
  2109. :param client_id: id of client (not client-id)
  2110. :type client_id: str
  2111. :param roles: roles list or role (use RoleRepresentation)
  2112. :type roles: list
  2113. :return: Keycloak server response
  2114. :rtype: bytes
  2115. """
  2116. payload = roles if isinstance(roles, list) else [roles]
  2117. params_path = {
  2118. "realm-name": self.connection.realm_name,
  2119. "id": user_id,
  2120. "client-id": client_id,
  2121. }
  2122. data_raw = self.connection.raw_post(
  2123. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  2124. data=json.dumps(payload),
  2125. )
  2126. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2127. def get_client_role_members(self, client_id, role_name, **query):
  2128. """Get members by client role.
  2129. :param client_id: The client id
  2130. :type client_id: str
  2131. :param role_name: the name of role to be queried.
  2132. :type role_name: str
  2133. :param query: Additional query parameters
  2134. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource)
  2135. :type query: dict
  2136. :return: Keycloak server response (UserRepresentation)
  2137. :rtype: list
  2138. """
  2139. params_path = {
  2140. "realm-name": self.connection.realm_name,
  2141. "id": client_id,
  2142. "role-name": role_name,
  2143. }
  2144. return self.__fetch_all(
  2145. urls_patterns.URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path), query
  2146. )
  2147. def get_client_role_groups(self, client_id, role_name, **query):
  2148. """Get group members by client role.
  2149. :param client_id: The client id
  2150. :type client_id: str
  2151. :param role_name: the name of role to be queried.
  2152. :type role_name: str
  2153. :param query: Additional query parameters
  2154. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource)
  2155. :type query: dict
  2156. :return: Keycloak server response
  2157. :rtype: list
  2158. """
  2159. params_path = {
  2160. "realm-name": self.connection.realm_name,
  2161. "id": client_id,
  2162. "role-name": role_name,
  2163. }
  2164. return self.__fetch_all(
  2165. urls_patterns.URL_ADMIN_CLIENT_ROLE_GROUPS.format(**params_path), query
  2166. )
  2167. def get_role_by_id(self, role_id):
  2168. """Get a specific role’s representation.
  2169. RoleRepresentation
  2170. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2171. :param role_id: id of role
  2172. :type role_id: str
  2173. :return: Keycloak server response (RoleRepresentation)
  2174. :rtype: bytes
  2175. """
  2176. params_path = {"realm-name": self.connection.realm_name, "role-id": role_id}
  2177. data_raw = self.connection.raw_get(
  2178. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_ID.format(**params_path)
  2179. )
  2180. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  2181. def update_role_by_id(self, role_id, payload):
  2182. """Update the role.
  2183. RoleRepresentation
  2184. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2185. :param payload: RoleRepresentation
  2186. :type payload: dict
  2187. :param role_id: id of role
  2188. :type role_id: str
  2189. :returns: Keycloak server response
  2190. :rtype: bytes
  2191. """
  2192. params_path = {"realm-name": self.connection.realm_name, "role-id": role_id}
  2193. data_raw = self.connection.raw_put(
  2194. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_ID.format(**params_path),
  2195. data=json.dumps(payload),
  2196. )
  2197. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  2198. def delete_role_by_id(self, role_id):
  2199. """Delete a role by its id.
  2200. RoleRepresentation
  2201. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2202. :param role_id: id of role
  2203. :type role_id: str
  2204. :returns: Keycloak server response
  2205. :rtype: bytes
  2206. """
  2207. params_path = {"realm-name": self.connection.realm_name, "role-id": role_id}
  2208. data_raw = self.connection.raw_delete(
  2209. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_ID.format(**params_path)
  2210. )
  2211. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2212. def create_realm_role(self, payload, skip_exists=False):
  2213. """Create a new role for the realm or client.
  2214. :param payload: The role (use RoleRepresentation)
  2215. :type payload: dict
  2216. :param skip_exists: If true then do not raise an error if realm role already exists
  2217. :type skip_exists: bool
  2218. :return: Realm role name
  2219. :rtype: str
  2220. """
  2221. if skip_exists:
  2222. try:
  2223. role = self.get_realm_role(role_name=payload["name"])
  2224. return role["name"]
  2225. except KeycloakGetError:
  2226. pass
  2227. params_path = {"realm-name": self.connection.realm_name}
  2228. data_raw = self.connection.raw_post(
  2229. urls_patterns.URL_ADMIN_REALM_ROLES.format(**params_path), data=json.dumps(payload)
  2230. )
  2231. raise_error_from_response(
  2232. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  2233. )
  2234. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  2235. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  2236. def get_realm_role(self, role_name):
  2237. """Get realm role by role name.
  2238. RoleRepresentation
  2239. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2240. :param role_name: role's name, not id!
  2241. :type role_name: str
  2242. :return: role
  2243. :rtype: dict
  2244. """
  2245. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2246. data_raw = self.connection.raw_get(
  2247. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path)
  2248. )
  2249. return raise_error_from_response(data_raw, KeycloakGetError)
  2250. def get_realm_role_by_id(self, role_id: str):
  2251. """Get realm role by role id.
  2252. RoleRepresentation
  2253. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  2254. :param role_id: role's id, not name!
  2255. :type role_id: str
  2256. :return: role
  2257. :rtype: dict
  2258. """
  2259. params_path = {"realm-name": self.connection.realm_name, "role-id": role_id}
  2260. data_raw = self.connection.raw_get(
  2261. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_ID.format(**params_path)
  2262. )
  2263. return raise_error_from_response(data_raw, KeycloakGetError)
  2264. def update_realm_role(self, role_name, payload):
  2265. """Update a role for the realm by name.
  2266. :param role_name: The name of the role to be updated
  2267. :type role_name: str
  2268. :param payload: The role (use RoleRepresentation)
  2269. :type payload: dict
  2270. :return: Keycloak server response
  2271. :rtype: bytes
  2272. """
  2273. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2274. data_raw = self.connection.raw_put(
  2275. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  2276. data=json.dumps(payload),
  2277. )
  2278. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  2279. def delete_realm_role(self, role_name):
  2280. """Delete a role for the realm by name.
  2281. :param role_name: The role name
  2282. :type role_name: str
  2283. :return: Keycloak server response
  2284. :rtype: bytes
  2285. """
  2286. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2287. data_raw = self.connection.raw_delete(
  2288. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path)
  2289. )
  2290. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2291. def add_composite_realm_roles_to_role(self, role_name, roles):
  2292. """Add composite roles to the role.
  2293. :param role_name: The name of the role
  2294. :type role_name: str
  2295. :param roles: roles list or role (use RoleRepresentation) to be updated
  2296. :type roles: list
  2297. :return: Keycloak server response
  2298. :rtype: bytes
  2299. """
  2300. payload = roles if isinstance(roles, list) else [roles]
  2301. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2302. data_raw = self.connection.raw_post(
  2303. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  2304. data=json.dumps(payload),
  2305. )
  2306. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2307. def remove_composite_realm_roles_to_role(self, role_name, roles):
  2308. """Remove composite roles from the role.
  2309. :param role_name: The name of the role
  2310. :type role_name: str
  2311. :param roles: roles list or role (use RoleRepresentation) to be removed
  2312. :type roles: list
  2313. :return: Keycloak server response
  2314. :rtype: bytes
  2315. """
  2316. payload = roles if isinstance(roles, list) else [roles]
  2317. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2318. data_raw = self.connection.raw_delete(
  2319. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  2320. data=json.dumps(payload),
  2321. )
  2322. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2323. def get_composite_realm_roles_of_role(self, role_name):
  2324. """Get composite roles of the role.
  2325. :param role_name: The name of the role
  2326. :type role_name: str
  2327. :return: Keycloak server response (array RoleRepresentation)
  2328. :rtype: list
  2329. """
  2330. params_path = {"realm-name": self.connection.realm_name, "role-name": role_name}
  2331. data_raw = self.connection.raw_get(
  2332. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path)
  2333. )
  2334. return raise_error_from_response(data_raw, KeycloakGetError)
  2335. def assign_realm_roles_to_client_scope(self, client_id, roles):
  2336. """Assign realm roles to a client's scope.
  2337. :param client_id: id of client (not client-id)
  2338. :type client_id: str
  2339. :param roles: roles list or role (use RoleRepresentation)
  2340. :type roles: list
  2341. :return: Keycloak server response
  2342. :rtype: dict
  2343. """
  2344. payload = roles if isinstance(roles, list) else [roles]
  2345. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  2346. data_raw = self.connection.raw_post(
  2347. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_REALM_ROLES.format(**params_path),
  2348. data=json.dumps(payload),
  2349. )
  2350. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2351. def delete_realm_roles_of_client_scope(self, client_id, roles):
  2352. """Delete realm roles of a client's scope.
  2353. :param client_id: id of client (not client-id)
  2354. :type client_id: str
  2355. :param roles: roles list or role (use RoleRepresentation)
  2356. :type roles: list
  2357. :return: Keycloak server response
  2358. :rtype: dict
  2359. """
  2360. payload = roles if isinstance(roles, list) else [roles]
  2361. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  2362. data_raw = self.connection.raw_delete(
  2363. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_REALM_ROLES.format(**params_path),
  2364. data=json.dumps(payload),
  2365. )
  2366. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2367. def get_realm_roles_of_client_scope(self, client_id):
  2368. """Get all realm roles for a client's scope.
  2369. :param client_id: id of client (not client-id)
  2370. :type client_id: str
  2371. :return: Keycloak server response (array RoleRepresentation)
  2372. :rtype: dict
  2373. """
  2374. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  2375. data_raw = self.connection.raw_get(
  2376. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_REALM_ROLES.format(**params_path)
  2377. )
  2378. return raise_error_from_response(data_raw, KeycloakGetError)
  2379. def assign_client_roles_to_client_scope(self, client_id, client_roles_owner_id, roles):
  2380. """Assign client roles to a client's scope.
  2381. :param client_id: id of client (not client-id) who is assigned the roles
  2382. :type client_id: str
  2383. :param client_roles_owner_id: id of client (not client-id) who has the roles
  2384. :type client_roles_owner_id: str
  2385. :param roles: roles list or role (use RoleRepresentation)
  2386. :type roles: list
  2387. :return: Keycloak server response
  2388. :rtype: dict
  2389. """
  2390. payload = roles if isinstance(roles, list) else [roles]
  2391. params_path = {
  2392. "realm-name": self.connection.realm_name,
  2393. "id": client_id,
  2394. "client": client_roles_owner_id,
  2395. }
  2396. data_raw = self.connection.raw_post(
  2397. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_CLIENT_ROLES.format(**params_path),
  2398. data=json.dumps(payload),
  2399. )
  2400. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2401. def delete_client_roles_of_client_scope(self, client_id, client_roles_owner_id, roles):
  2402. """Delete client roles of a client's scope.
  2403. :param client_id: id of client (not client-id) who is assigned the roles
  2404. :type client_id: str
  2405. :param client_roles_owner_id: id of client (not client-id) who has the roles
  2406. :type client_roles_owner_id: str
  2407. :param roles: roles list or role (use RoleRepresentation)
  2408. :type roles: list
  2409. :return: Keycloak server response
  2410. :rtype: dict
  2411. """
  2412. payload = roles if isinstance(roles, list) else [roles]
  2413. params_path = {
  2414. "realm-name": self.connection.realm_name,
  2415. "id": client_id,
  2416. "client": client_roles_owner_id,
  2417. }
  2418. data_raw = self.connection.raw_delete(
  2419. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_CLIENT_ROLES.format(**params_path),
  2420. data=json.dumps(payload),
  2421. )
  2422. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2423. def get_client_roles_of_client_scope(self, client_id, client_roles_owner_id):
  2424. """Get all client roles for a client's scope.
  2425. :param client_id: id of client (not client-id)
  2426. :type client_id: str
  2427. :param client_roles_owner_id: id of client (not client-id) who has the roles
  2428. :type client_roles_owner_id: str
  2429. :return: Keycloak server response (array RoleRepresentation)
  2430. :rtype: dict
  2431. """
  2432. params_path = {
  2433. "realm-name": self.connection.realm_name,
  2434. "id": client_id,
  2435. "client": client_roles_owner_id,
  2436. }
  2437. data_raw = self.connection.raw_get(
  2438. urls_patterns.URL_ADMIN_CLIENT_SCOPE_MAPPINGS_CLIENT_ROLES.format(**params_path)
  2439. )
  2440. return raise_error_from_response(data_raw, KeycloakGetError)
  2441. def assign_realm_roles(self, user_id, roles):
  2442. """Assign realm roles to a user.
  2443. :param user_id: id of user
  2444. :type user_id: str
  2445. :param roles: roles list or role (use RoleRepresentation)
  2446. :type roles: list
  2447. :return: Keycloak server response
  2448. :rtype: bytes
  2449. """
  2450. payload = roles if isinstance(roles, list) else [roles]
  2451. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  2452. data_raw = self.connection.raw_post(
  2453. urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  2454. data=json.dumps(payload),
  2455. )
  2456. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2457. def delete_realm_roles_of_user(self, user_id, roles):
  2458. """Delete realm roles of a user.
  2459. :param user_id: id of user
  2460. :type user_id: str
  2461. :param roles: roles list or role (use RoleRepresentation)
  2462. :type roles: list
  2463. :return: Keycloak server response
  2464. :rtype: bytes
  2465. """
  2466. payload = roles if isinstance(roles, list) else [roles]
  2467. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  2468. data_raw = self.connection.raw_delete(
  2469. urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  2470. data=json.dumps(payload),
  2471. )
  2472. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2473. def get_realm_roles_of_user(self, user_id):
  2474. """Get all realm roles for a user.
  2475. :param user_id: id of user
  2476. :type user_id: str
  2477. :return: Keycloak server response (array RoleRepresentation)
  2478. :rtype: list
  2479. """
  2480. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  2481. data_raw = self.connection.raw_get(
  2482. urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path)
  2483. )
  2484. return raise_error_from_response(data_raw, KeycloakGetError)
  2485. def get_available_realm_roles_of_user(self, user_id):
  2486. """Get all available (i.e. unassigned) realm roles for a user.
  2487. :param user_id: id of user
  2488. :type user_id: str
  2489. :return: Keycloak server response (array RoleRepresentation)
  2490. :rtype: list
  2491. """
  2492. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  2493. data_raw = self.connection.raw_get(
  2494. urls_patterns.URL_ADMIN_USER_REALM_ROLES_AVAILABLE.format(**params_path)
  2495. )
  2496. return raise_error_from_response(data_raw, KeycloakGetError)
  2497. def get_composite_realm_roles_of_user(self, user_id, brief_representation=True):
  2498. """Get all composite (i.e. implicit) realm roles for a user.
  2499. :param user_id: id of user
  2500. :type user_id: str
  2501. :param brief_representation: whether to omit role attributes in the response
  2502. :type brief_representation: bool
  2503. :return: Keycloak server response (array RoleRepresentation)
  2504. :rtype: list
  2505. """
  2506. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  2507. params = {"briefRepresentation": brief_representation}
  2508. data_raw = self.connection.raw_get(
  2509. urls_patterns.URL_ADMIN_USER_REALM_ROLES_COMPOSITE.format(**params_path), **params
  2510. )
  2511. return raise_error_from_response(data_raw, KeycloakGetError)
  2512. def assign_group_realm_roles(self, group_id, roles):
  2513. """Assign realm roles to a group.
  2514. :param group_id: id of group
  2515. :type group_id: str
  2516. :param roles: roles list or role (use GroupRoleRepresentation)
  2517. :type roles: list
  2518. :return: Keycloak server response
  2519. :rtype: bytes
  2520. """
  2521. payload = roles if isinstance(roles, list) else [roles]
  2522. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  2523. data_raw = self.connection.raw_post(
  2524. urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  2525. data=json.dumps(payload),
  2526. )
  2527. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2528. def delete_group_realm_roles(self, group_id, roles):
  2529. """Delete realm roles of a group.
  2530. :param group_id: id of group
  2531. :type group_id: str
  2532. :param roles: roles list or role (use GroupRoleRepresentation)
  2533. :type roles: list
  2534. :return: Keycloak server response
  2535. :rtype: bytes
  2536. """
  2537. payload = roles if isinstance(roles, list) else [roles]
  2538. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  2539. data_raw = self.connection.raw_delete(
  2540. urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  2541. data=json.dumps(payload),
  2542. )
  2543. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2544. def get_group_realm_roles(self, group_id, brief_representation=True):
  2545. """Get all realm roles for a group.
  2546. :param group_id: id of the group
  2547. :type group_id: str
  2548. :param brief_representation: whether to omit role attributes in the response
  2549. :type brief_representation: bool
  2550. :return: Keycloak server response (array RoleRepresentation)
  2551. :rtype: list
  2552. """
  2553. params_path = {"realm-name": self.connection.realm_name, "id": group_id}
  2554. params = {"briefRepresentation": brief_representation}
  2555. data_raw = self.connection.raw_get(
  2556. urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path), **params
  2557. )
  2558. return raise_error_from_response(data_raw, KeycloakGetError)
  2559. def assign_group_client_roles(self, group_id, client_id, roles):
  2560. """Assign client roles to a group.
  2561. :param group_id: id of group
  2562. :type group_id: str
  2563. :param client_id: id of client (not client-id)
  2564. :type client_id: str
  2565. :param roles: roles list or role (use GroupRoleRepresentation)
  2566. :type roles: list
  2567. :return: Keycloak server response
  2568. :rtype: bytes
  2569. """
  2570. payload = roles if isinstance(roles, list) else [roles]
  2571. params_path = {
  2572. "realm-name": self.connection.realm_name,
  2573. "id": group_id,
  2574. "client-id": client_id,
  2575. }
  2576. data_raw = self.connection.raw_post(
  2577. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  2578. data=json.dumps(payload),
  2579. )
  2580. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  2581. def get_group_client_roles(self, group_id, client_id):
  2582. """Get client roles of a group.
  2583. :param group_id: id of group
  2584. :type group_id: str
  2585. :param client_id: id of client (not client-id)
  2586. :type client_id: str
  2587. :return: Keycloak server response
  2588. :rtype: list
  2589. """
  2590. params_path = {
  2591. "realm-name": self.connection.realm_name,
  2592. "id": group_id,
  2593. "client-id": client_id,
  2594. }
  2595. data_raw = self.connection.raw_get(
  2596. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path)
  2597. )
  2598. return raise_error_from_response(data_raw, KeycloakGetError)
  2599. def delete_group_client_roles(self, group_id, client_id, roles):
  2600. """Delete client roles of a group.
  2601. :param group_id: id of group
  2602. :type group_id: str
  2603. :param client_id: id of client (not client-id)
  2604. :type client_id: str
  2605. :param roles: roles list or role (use GroupRoleRepresentation)
  2606. :type roles: list
  2607. :return: Keycloak server response (array RoleRepresentation)
  2608. :rtype: bytes
  2609. """
  2610. payload = roles if isinstance(roles, list) else [roles]
  2611. params_path = {
  2612. "realm-name": self.connection.realm_name,
  2613. "id": group_id,
  2614. "client-id": client_id,
  2615. }
  2616. data_raw = self.connection.raw_delete(
  2617. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  2618. data=json.dumps(payload),
  2619. )
  2620. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2621. def get_client_roles_of_user(self, user_id, client_id):
  2622. """Get all client roles for a user.
  2623. :param user_id: id of user
  2624. :type user_id: str
  2625. :param client_id: id of client (not client-id)
  2626. :type client_id: str
  2627. :return: Keycloak server response (array RoleRepresentation)
  2628. :rtype: list
  2629. """
  2630. return self._get_client_roles_of_user(
  2631. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id
  2632. )
  2633. def get_available_client_roles_of_user(self, user_id, client_id):
  2634. """Get available client role-mappings for a user.
  2635. :param user_id: id of user
  2636. :type user_id: str
  2637. :param client_id: id of client (not client-id)
  2638. :type client_id: str
  2639. :return: Keycloak server response (array RoleRepresentation)
  2640. :rtype: list
  2641. """
  2642. return self._get_client_roles_of_user(
  2643. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id
  2644. )
  2645. def get_composite_client_roles_of_user(self, user_id, client_id, brief_representation=False):
  2646. """Get composite client role-mappings for a user.
  2647. :param user_id: id of user
  2648. :type user_id: str
  2649. :param client_id: id of client (not client-id)
  2650. :type client_id: str
  2651. :param brief_representation: whether to omit attributes in the response
  2652. :type brief_representation: bool
  2653. :return: Keycloak server response (array RoleRepresentation)
  2654. :rtype: list
  2655. """
  2656. params = {"briefRepresentation": brief_representation}
  2657. return self._get_client_roles_of_user(
  2658. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id, **params
  2659. )
  2660. def _get_client_roles_of_user(
  2661. self, client_level_role_mapping_url, user_id, client_id, **params
  2662. ):
  2663. """Get client roles of a single user helper.
  2664. :param client_level_role_mapping_url: Url for the client role mapping
  2665. :type client_level_role_mapping_url: str
  2666. :param user_id: User id
  2667. :type user_id: str
  2668. :param client_id: Client id
  2669. :type client_id: str
  2670. :param params: Additional parameters
  2671. :type params: dict
  2672. :returns: Client roles of a user
  2673. :rtype: list
  2674. """
  2675. params_path = {
  2676. "realm-name": self.connection.realm_name,
  2677. "id": user_id,
  2678. "client-id": client_id,
  2679. }
  2680. data_raw = self.connection.raw_get(
  2681. client_level_role_mapping_url.format(**params_path), **params
  2682. )
  2683. return raise_error_from_response(data_raw, KeycloakGetError)
  2684. def delete_client_roles_of_user(self, user_id, client_id, roles):
  2685. """Delete client roles from a user.
  2686. :param user_id: id of user
  2687. :type user_id: str
  2688. :param client_id: id of client containing role (not client-id)
  2689. :type client_id: str
  2690. :param roles: roles list or role to delete (use RoleRepresentation)
  2691. :type roles: list
  2692. :return: Keycloak server response
  2693. :rtype: bytes
  2694. """
  2695. payload = roles if isinstance(roles, list) else [roles]
  2696. params_path = {
  2697. "realm-name": self.connection.realm_name,
  2698. "id": user_id,
  2699. "client-id": client_id,
  2700. }
  2701. data_raw = self.connection.raw_delete(
  2702. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  2703. data=json.dumps(payload),
  2704. )
  2705. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2706. def get_authentication_flows(self):
  2707. """Get authentication flows.
  2708. Returns all flow details
  2709. AuthenticationFlowRepresentation
  2710. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  2711. :return: Keycloak server response (AuthenticationFlowRepresentation)
  2712. :rtype: list
  2713. """
  2714. params_path = {"realm-name": self.connection.realm_name}
  2715. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_FLOWS.format(**params_path))
  2716. return raise_error_from_response(data_raw, KeycloakGetError)
  2717. def get_authentication_flow_for_id(self, flow_id):
  2718. """Get one authentication flow by it's id.
  2719. Returns all flow details
  2720. AuthenticationFlowRepresentation
  2721. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  2722. :param flow_id: the id of a flow NOT it's alias
  2723. :type flow_id: str
  2724. :return: Keycloak server response (AuthenticationFlowRepresentation)
  2725. :rtype: dict
  2726. """
  2727. params_path = {"realm-name": self.connection.realm_name, "flow-id": flow_id}
  2728. data_raw = self.connection.raw_get(
  2729. urls_patterns.URL_ADMIN_FLOWS_ALIAS.format(**params_path)
  2730. )
  2731. return raise_error_from_response(data_raw, KeycloakGetError)
  2732. def create_authentication_flow(self, payload, skip_exists=False):
  2733. """Create a new authentication flow.
  2734. AuthenticationFlowRepresentation
  2735. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  2736. :param payload: AuthenticationFlowRepresentation
  2737. :type payload: dict
  2738. :param skip_exists: Do not raise an error if authentication flow already exists
  2739. :type skip_exists: bool
  2740. :return: Keycloak server response (RoleRepresentation)
  2741. :rtype: bytes
  2742. """
  2743. params_path = {"realm-name": self.connection.realm_name}
  2744. data_raw = self.connection.raw_post(
  2745. urls_patterns.URL_ADMIN_FLOWS.format(**params_path), data=json.dumps(payload)
  2746. )
  2747. return raise_error_from_response(
  2748. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  2749. )
  2750. def copy_authentication_flow(self, payload, flow_alias):
  2751. """Copy existing authentication flow under a new name.
  2752. The new name is given as 'newName' attribute of the passed payload.
  2753. :param payload: JSON containing 'newName' attribute
  2754. :type payload: dict
  2755. :param flow_alias: the flow alias
  2756. :type flow_alias: str
  2757. :return: Keycloak server response (RoleRepresentation)
  2758. :rtype: bytes
  2759. """
  2760. params_path = {"realm-name": self.connection.realm_name, "flow-alias": flow_alias}
  2761. data_raw = self.connection.raw_post(
  2762. urls_patterns.URL_ADMIN_FLOWS_COPY.format(**params_path), data=json.dumps(payload)
  2763. )
  2764. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  2765. def delete_authentication_flow(self, flow_id):
  2766. """Delete authentication flow.
  2767. AuthenticationInfoRepresentation
  2768. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationinforepresentation
  2769. :param flow_id: authentication flow id
  2770. :type flow_id: str
  2771. :return: Keycloak server response
  2772. :rtype: bytes
  2773. """
  2774. params_path = {"realm-name": self.connection.realm_name, "id": flow_id}
  2775. data_raw = self.connection.raw_delete(urls_patterns.URL_ADMIN_FLOW.format(**params_path))
  2776. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2777. def get_authentication_flow_executions(self, flow_alias):
  2778. """Get authentication flow executions.
  2779. Returns all execution steps
  2780. :param flow_alias: the flow alias
  2781. :type flow_alias: str
  2782. :return: Response(json)
  2783. :rtype: list
  2784. """
  2785. params_path = {"realm-name": self.connection.realm_name, "flow-alias": flow_alias}
  2786. data_raw = self.connection.raw_get(
  2787. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path)
  2788. )
  2789. return raise_error_from_response(data_raw, KeycloakGetError)
  2790. def update_authentication_flow_executions(self, payload, flow_alias):
  2791. """Update an authentication flow execution.
  2792. AuthenticationExecutionInfoRepresentation
  2793. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  2794. :param payload: AuthenticationExecutionInfoRepresentation
  2795. :type payload: dict
  2796. :param flow_alias: The flow alias
  2797. :type flow_alias: str
  2798. :return: Keycloak server response
  2799. :rtype: bytes
  2800. """
  2801. params_path = {"realm-name": self.connection.realm_name, "flow-alias": flow_alias}
  2802. data_raw = self.connection.raw_put(
  2803. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  2804. data=json.dumps(payload),
  2805. )
  2806. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[202, 204])
  2807. def get_authentication_flow_execution(self, execution_id):
  2808. """Get authentication flow execution.
  2809. AuthenticationExecutionInfoRepresentation
  2810. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  2811. :param execution_id: the execution ID
  2812. :type execution_id: str
  2813. :return: Response(json)
  2814. :rtype: dict
  2815. """
  2816. params_path = {"realm-name": self.connection.realm_name, "id": execution_id}
  2817. data_raw = self.connection.raw_get(
  2818. urls_patterns.URL_ADMIN_FLOWS_EXECUTION.format(**params_path)
  2819. )
  2820. return raise_error_from_response(data_raw, KeycloakGetError)
  2821. def create_authentication_flow_execution(self, payload, flow_alias):
  2822. """Create an authentication flow execution.
  2823. AuthenticationExecutionInfoRepresentation
  2824. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  2825. :param payload: AuthenticationExecutionInfoRepresentation
  2826. :type payload: dict
  2827. :param flow_alias: The flow alias
  2828. :type flow_alias: str
  2829. :return: Keycloak server response
  2830. :rtype: bytes
  2831. """
  2832. params_path = {"realm-name": self.connection.realm_name, "flow-alias": flow_alias}
  2833. data_raw = self.connection.raw_post(
  2834. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS_EXECUTION.format(**params_path),
  2835. data=json.dumps(payload),
  2836. )
  2837. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  2838. def delete_authentication_flow_execution(self, execution_id):
  2839. """Delete authentication flow execution.
  2840. AuthenticationExecutionInfoRepresentation
  2841. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  2842. :param execution_id: keycloak client id (not oauth client-id)
  2843. :type execution_id: str
  2844. :return: Keycloak server response (json)
  2845. :rtype: bytes
  2846. """
  2847. params_path = {"realm-name": self.connection.realm_name, "id": execution_id}
  2848. data_raw = self.connection.raw_delete(
  2849. urls_patterns.URL_ADMIN_FLOWS_EXECUTION.format(**params_path)
  2850. )
  2851. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2852. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  2853. """Create a new sub authentication flow for a given authentication flow.
  2854. AuthenticationFlowRepresentation
  2855. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  2856. :param payload: AuthenticationFlowRepresentation
  2857. :type payload: dict
  2858. :param flow_alias: The flow alias
  2859. :type flow_alias: str
  2860. :param skip_exists: Do not raise an error if authentication flow already exists
  2861. :type skip_exists: bool
  2862. :return: Keycloak server response (RoleRepresentation)
  2863. :rtype: bytes
  2864. """
  2865. params_path = {"realm-name": self.connection.realm_name, "flow-alias": flow_alias}
  2866. data_raw = self.connection.raw_post(
  2867. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  2868. data=json.dumps(payload),
  2869. )
  2870. return raise_error_from_response(
  2871. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  2872. )
  2873. def get_authenticator_providers(self):
  2874. """Get authenticator providers list.
  2875. :return: Authenticator providers
  2876. :rtype: list
  2877. """
  2878. params_path = {"realm-name": self.connection.realm_name}
  2879. data_raw = self.connection.raw_get(
  2880. urls_patterns.URL_ADMIN_AUTHENTICATOR_PROVIDERS.format(**params_path)
  2881. )
  2882. return raise_error_from_response(data_raw, KeycloakGetError)
  2883. def get_authenticator_provider_config_description(self, provider_id):
  2884. """Get authenticator's provider configuration description.
  2885. AuthenticatorConfigInfoRepresentation
  2886. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfiginforepresentation
  2887. :param provider_id: Provider Id
  2888. :type provider_id: str
  2889. :return: AuthenticatorConfigInfoRepresentation
  2890. :rtype: dict
  2891. """
  2892. params_path = {"realm-name": self.connection.realm_name, "provider-id": provider_id}
  2893. data_raw = self.connection.raw_get(
  2894. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG_DESCRIPTION.format(**params_path)
  2895. )
  2896. return raise_error_from_response(data_raw, KeycloakGetError)
  2897. def get_authenticator_config(self, config_id):
  2898. """Get authenticator configuration.
  2899. Returns all configuration details.
  2900. :param config_id: Authenticator config id
  2901. :type config_id: str
  2902. :return: Response(json)
  2903. :rtype: dict
  2904. """
  2905. params_path = {"realm-name": self.connection.realm_name, "id": config_id}
  2906. data_raw = self.connection.raw_get(
  2907. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path)
  2908. )
  2909. return raise_error_from_response(data_raw, KeycloakGetError)
  2910. def update_authenticator_config(self, payload, config_id):
  2911. """Update an authenticator configuration.
  2912. AuthenticatorConfigRepresentation
  2913. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfigrepresentation
  2914. :param payload: AuthenticatorConfigRepresentation
  2915. :type payload: dict
  2916. :param config_id: Authenticator config id
  2917. :type config_id: str
  2918. :return: Response(json)
  2919. :rtype: bytes
  2920. """
  2921. params_path = {"realm-name": self.connection.realm_name, "id": config_id}
  2922. data_raw = self.connection.raw_put(
  2923. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  2924. data=json.dumps(payload),
  2925. )
  2926. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  2927. def delete_authenticator_config(self, config_id):
  2928. """Delete a authenticator configuration.
  2929. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authentication_management_resource
  2930. :param config_id: Authenticator config id
  2931. :type config_id: str
  2932. :return: Keycloak server Response
  2933. :rtype: bytes
  2934. """
  2935. params_path = {"realm-name": self.connection.realm_name, "id": config_id}
  2936. data_raw = self.connection.raw_delete(
  2937. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path)
  2938. )
  2939. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  2940. def sync_users(self, storage_id, action):
  2941. """Trigger user sync from provider.
  2942. :param storage_id: The id of the user storage provider
  2943. :type storage_id: str
  2944. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  2945. :type action: str
  2946. :return: Keycloak server response
  2947. :rtype: bytes
  2948. """
  2949. data = {"action": action}
  2950. params_query = {"action": action}
  2951. params_path = {"realm-name": self.connection.realm_name, "id": storage_id}
  2952. data_raw = self.connection.raw_post(
  2953. urls_patterns.URL_ADMIN_USER_STORAGE.format(**params_path),
  2954. data=json.dumps(data),
  2955. **params_query,
  2956. )
  2957. return raise_error_from_response(data_raw, KeycloakPostError)
  2958. def get_client_scopes(self):
  2959. """Get client scopes.
  2960. Get representation of the client scopes for the realm where we are connected to
  2961. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  2962. :return: Keycloak server response Array of (ClientScopeRepresentation)
  2963. :rtype: list
  2964. """
  2965. params_path = {"realm-name": self.connection.realm_name}
  2966. data_raw = self.connection.raw_get(
  2967. urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path)
  2968. )
  2969. return raise_error_from_response(data_raw, KeycloakGetError)
  2970. def get_client_scope(self, client_scope_id):
  2971. """Get client scope.
  2972. Get representation of the client scopes for the realm where we are connected to
  2973. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  2974. :param client_scope_id: The id of the client scope
  2975. :type client_scope_id: str
  2976. :return: Keycloak server response (ClientScopeRepresentation)
  2977. :rtype: dict
  2978. """
  2979. params_path = {"realm-name": self.connection.realm_name, "scope-id": client_scope_id}
  2980. data_raw = self.connection.raw_get(
  2981. urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path)
  2982. )
  2983. return raise_error_from_response(data_raw, KeycloakGetError)
  2984. def get_client_scope_by_name(self, client_scope_name):
  2985. """Get client scope by name.
  2986. Get representation of the client scope identified by the client scope name.
  2987. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  2988. :param client_scope_name: (str) Name of the client scope
  2989. :type client_scope_name: str
  2990. :returns: ClientScopeRepresentation or None
  2991. :rtype: dict
  2992. """
  2993. client_scopes = self.get_client_scopes()
  2994. for client_scope in client_scopes:
  2995. if client_scope["name"] == client_scope_name:
  2996. return client_scope
  2997. return None
  2998. def create_client_scope(self, payload, skip_exists=False):
  2999. """Create a client scope.
  3000. ClientScopeRepresentation:
  3001. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  3002. :param payload: ClientScopeRepresentation
  3003. :type payload: dict
  3004. :param skip_exists: If true then do not raise an error if client scope already exists
  3005. :type skip_exists: bool
  3006. :return: Client scope id
  3007. :rtype: str
  3008. """
  3009. if skip_exists:
  3010. exists = self.get_client_scope_by_name(client_scope_name=payload["name"])
  3011. if exists is not None:
  3012. return exists["id"]
  3013. params_path = {"realm-name": self.connection.realm_name}
  3014. data_raw = self.connection.raw_post(
  3015. urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path), data=json.dumps(payload)
  3016. )
  3017. raise_error_from_response(
  3018. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  3019. )
  3020. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  3021. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  3022. def update_client_scope(self, client_scope_id, payload):
  3023. """Update a client scope.
  3024. ClientScopeRepresentation:
  3025. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource
  3026. :param client_scope_id: The id of the client scope
  3027. :type client_scope_id: str
  3028. :param payload: ClientScopeRepresentation
  3029. :type payload: dict
  3030. :return: Keycloak server response (ClientScopeRepresentation)
  3031. :rtype: bytes
  3032. """
  3033. params_path = {"realm-name": self.connection.realm_name, "scope-id": client_scope_id}
  3034. data_raw = self.connection.raw_put(
  3035. urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path), data=json.dumps(payload)
  3036. )
  3037. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3038. def delete_client_scope(self, client_scope_id):
  3039. """Delete existing client scope.
  3040. ClientScopeRepresentation:
  3041. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource
  3042. :param client_scope_id: The id of the client scope
  3043. :type client_scope_id: str
  3044. :return: Keycloak server response
  3045. :rtype: bytes
  3046. """
  3047. params_path = {"realm-name": self.connection.realm_name, "scope-id": client_scope_id}
  3048. data_raw = self.connection.raw_delete(
  3049. urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path)
  3050. )
  3051. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3052. def get_mappers_from_client_scope(self, client_scope_id):
  3053. """Get a list of all mappers connected to the client scope.
  3054. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource
  3055. :param client_scope_id: Client scope id
  3056. :type client_scope_id: str
  3057. :returns: Keycloak server response (ProtocolMapperRepresentation)
  3058. :rtype: list
  3059. """
  3060. params_path = {"realm-name": self.connection.realm_name, "scope-id": client_scope_id}
  3061. data_raw = self.connection.raw_get(
  3062. urls_patterns.URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path)
  3063. )
  3064. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  3065. def add_mapper_to_client_scope(self, client_scope_id, payload):
  3066. """Add a mapper to a client scope.
  3067. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  3068. :param client_scope_id: The id of the client scope
  3069. :type client_scope_id: str
  3070. :param payload: ProtocolMapperRepresentation
  3071. :type payload: dict
  3072. :return: Keycloak server Response
  3073. :rtype: bytes
  3074. """
  3075. params_path = {"realm-name": self.connection.realm_name, "scope-id": client_scope_id}
  3076. data_raw = self.connection.raw_post(
  3077. urls_patterns.URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path),
  3078. data=json.dumps(payload),
  3079. )
  3080. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  3081. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mapper_id):
  3082. """Delete a mapper from a client scope.
  3083. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_delete_mapper
  3084. :param client_scope_id: The id of the client scope
  3085. :type client_scope_id: str
  3086. :param protocol_mapper_id: Protocol mapper id
  3087. :type protocol_mapper_id: str
  3088. :return: Keycloak server Response
  3089. :rtype: bytes
  3090. """
  3091. params_path = {
  3092. "realm-name": self.connection.realm_name,
  3093. "scope-id": client_scope_id,
  3094. "protocol-mapper-id": protocol_mapper_id,
  3095. }
  3096. data_raw = self.connection.raw_delete(
  3097. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path)
  3098. )
  3099. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3100. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  3101. """Update an existing protocol mapper in a client scope.
  3102. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource
  3103. :param client_scope_id: The id of the client scope
  3104. :type client_scope_id: str
  3105. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  3106. and should to be updated
  3107. :type protocol_mapper_id: str
  3108. :param payload: ProtocolMapperRepresentation
  3109. :type payload: dict
  3110. :return: Keycloak server Response
  3111. :rtype: bytes
  3112. """
  3113. params_path = {
  3114. "realm-name": self.connection.realm_name,
  3115. "scope-id": client_scope_id,
  3116. "protocol-mapper-id": protocol_mapper_id,
  3117. }
  3118. data_raw = self.connection.raw_put(
  3119. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path),
  3120. data=json.dumps(payload),
  3121. )
  3122. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3123. def get_default_default_client_scopes(self):
  3124. """Get default default client scopes.
  3125. Return list of default default client scopes
  3126. :return: Keycloak server response
  3127. :rtype: list
  3128. """
  3129. params_path = {"realm-name": self.connection.realm_name}
  3130. data_raw = self.connection.raw_get(
  3131. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPES.format(**params_path)
  3132. )
  3133. return raise_error_from_response(data_raw, KeycloakGetError)
  3134. def delete_default_default_client_scope(self, scope_id):
  3135. """Delete default default client scope.
  3136. :param scope_id: default default client scope id
  3137. :type scope_id: str
  3138. :return: Keycloak server response
  3139. :rtype: list
  3140. """
  3141. params_path = {"realm-name": self.connection.realm_name, "id": scope_id}
  3142. data_raw = self.connection.raw_delete(
  3143. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path)
  3144. )
  3145. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3146. def add_default_default_client_scope(self, scope_id):
  3147. """Add default default client scope.
  3148. :param scope_id: default default client scope id
  3149. :type scope_id: str
  3150. :return: Keycloak server response
  3151. :rtype: bytes
  3152. """
  3153. params_path = {"realm-name": self.connection.realm_name, "id": scope_id}
  3154. payload = {"realm": self.connection.realm_name, "clientScopeId": scope_id}
  3155. data_raw = self.connection.raw_put(
  3156. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path),
  3157. data=json.dumps(payload),
  3158. )
  3159. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3160. def get_default_optional_client_scopes(self):
  3161. """Get default optional client scopes.
  3162. Return list of default optional client scopes
  3163. :return: Keycloak server response
  3164. :rtype: list
  3165. """
  3166. params_path = {"realm-name": self.connection.realm_name}
  3167. data_raw = self.connection.raw_get(
  3168. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPES.format(**params_path)
  3169. )
  3170. return raise_error_from_response(data_raw, KeycloakGetError)
  3171. def delete_default_optional_client_scope(self, scope_id):
  3172. """Delete default optional client scope.
  3173. :param scope_id: default optional client scope id
  3174. :type scope_id: str
  3175. :return: Keycloak server response
  3176. :rtype: bytes
  3177. """
  3178. params_path = {"realm-name": self.connection.realm_name, "id": scope_id}
  3179. data_raw = self.connection.raw_delete(
  3180. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path)
  3181. )
  3182. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3183. def add_default_optional_client_scope(self, scope_id):
  3184. """Add default optional client scope.
  3185. :param scope_id: default optional client scope id
  3186. :type scope_id: str
  3187. :return: Keycloak server response
  3188. :rtype: bytes
  3189. """
  3190. params_path = {"realm-name": self.connection.realm_name, "id": scope_id}
  3191. payload = {"realm": self.connection.realm_name, "clientScopeId": scope_id}
  3192. data_raw = self.connection.raw_put(
  3193. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path),
  3194. data=json.dumps(payload),
  3195. )
  3196. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3197. def get_mappers_from_client(self, client_id):
  3198. """List of all client mappers.
  3199. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocolmapperrepresentation
  3200. :param client_id: Client id
  3201. :type client_id: str
  3202. :returns: KeycloakServerResponse (list of ProtocolMapperRepresentation)
  3203. :rtype: list
  3204. """
  3205. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3206. data_raw = self.connection.raw_get(
  3207. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPERS.format(**params_path)
  3208. )
  3209. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[200])
  3210. def add_mapper_to_client(self, client_id, payload):
  3211. """Add a mapper to a client.
  3212. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  3213. :param client_id: The id of the client
  3214. :type client_id: str
  3215. :param payload: ProtocolMapperRepresentation
  3216. :type payload: dict
  3217. :return: Keycloak server Response
  3218. :rtype: bytes
  3219. """
  3220. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3221. data_raw = self.connection.raw_post(
  3222. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPERS.format(**params_path),
  3223. data=json.dumps(payload),
  3224. )
  3225. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  3226. def update_client_mapper(self, client_id, mapper_id, payload):
  3227. """Update client mapper.
  3228. :param client_id: The id of the client
  3229. :type client_id: str
  3230. :param mapper_id: The id of the mapper to be deleted
  3231. :type mapper_id: str
  3232. :param payload: ProtocolMapperRepresentation
  3233. :type payload: dict
  3234. :return: Keycloak server response
  3235. :rtype: bytes
  3236. """
  3237. params_path = {
  3238. "realm-name": self.connection.realm_name,
  3239. "id": client_id,
  3240. "protocol-mapper-id": mapper_id,
  3241. }
  3242. data_raw = self.connection.raw_put(
  3243. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path),
  3244. data=json.dumps(payload),
  3245. )
  3246. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3247. def remove_client_mapper(self, client_id, client_mapper_id):
  3248. """Remove a mapper from the client.
  3249. https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_protocol_mappers_resource
  3250. :param client_id: The id of the client
  3251. :type client_id: str
  3252. :param client_mapper_id: The id of the mapper to be deleted
  3253. :type client_mapper_id: str
  3254. :return: Keycloak server response
  3255. :rtype: bytes
  3256. """
  3257. params_path = {
  3258. "realm-name": self.connection.realm_name,
  3259. "id": client_id,
  3260. "protocol-mapper-id": client_mapper_id,
  3261. }
  3262. data_raw = self.connection.raw_delete(
  3263. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path)
  3264. )
  3265. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3266. def generate_client_secrets(self, client_id):
  3267. """Generate a new secret for the client.
  3268. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_regeneratesecret
  3269. :param client_id: id of client (not client-id)
  3270. :type client_id: str
  3271. :return: Keycloak server response (ClientRepresentation)
  3272. :rtype: bytes
  3273. """
  3274. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3275. data_raw = self.connection.raw_post(
  3276. urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None
  3277. )
  3278. return raise_error_from_response(data_raw, KeycloakPostError)
  3279. def get_client_secrets(self, client_id):
  3280. """Get representation of the client secrets.
  3281. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsecret
  3282. :param client_id: id of client (not client-id)
  3283. :type client_id: str
  3284. :return: Keycloak server response (ClientRepresentation)
  3285. :rtype: list
  3286. """
  3287. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3288. data_raw = self.connection.raw_get(
  3289. urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path)
  3290. )
  3291. return raise_error_from_response(data_raw, KeycloakGetError)
  3292. def get_components(self, query=None):
  3293. """Get components.
  3294. Return a list of components, filtered according to query parameters
  3295. ComponentRepresentation
  3296. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  3297. :param query: Query parameters (optional)
  3298. :type query: dict
  3299. :return: components list
  3300. :rtype: list
  3301. """
  3302. query = query or dict()
  3303. params_path = {"realm-name": self.connection.realm_name}
  3304. data_raw = self.connection.raw_get(
  3305. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=None, **query
  3306. )
  3307. return raise_error_from_response(data_raw, KeycloakGetError)
  3308. def create_component(self, payload):
  3309. """Create a new component.
  3310. ComponentRepresentation
  3311. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  3312. :param payload: ComponentRepresentation
  3313. :type payload: dict
  3314. :return: Component id
  3315. :rtype: str
  3316. """
  3317. params_path = {"realm-name": self.connection.realm_name}
  3318. data_raw = self.connection.raw_post(
  3319. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=json.dumps(payload)
  3320. )
  3321. raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  3322. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  3323. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  3324. def get_component(self, component_id):
  3325. """Get representation of the component.
  3326. :param component_id: Component id
  3327. ComponentRepresentation
  3328. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  3329. :param component_id: Id of the component
  3330. :type component_id: str
  3331. :return: ComponentRepresentation
  3332. :rtype: dict
  3333. """
  3334. params_path = {"realm-name": self.connection.realm_name, "component-id": component_id}
  3335. data_raw = self.connection.raw_get(urls_patterns.URL_ADMIN_COMPONENT.format(**params_path))
  3336. return raise_error_from_response(data_raw, KeycloakGetError)
  3337. def update_component(self, component_id, payload):
  3338. """Update the component.
  3339. :param component_id: Component id
  3340. :type component_id: str
  3341. :param payload: ComponentRepresentation
  3342. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  3343. :type payload: dict
  3344. :return: Http response
  3345. :rtype: bytes
  3346. """
  3347. params_path = {"realm-name": self.connection.realm_name, "component-id": component_id}
  3348. data_raw = self.connection.raw_put(
  3349. urls_patterns.URL_ADMIN_COMPONENT.format(**params_path), data=json.dumps(payload)
  3350. )
  3351. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3352. def delete_component(self, component_id):
  3353. """Delete the component.
  3354. :param component_id: Component id
  3355. :type component_id: str
  3356. :return: Http response
  3357. :rtype: bytes
  3358. """
  3359. params_path = {"realm-name": self.connection.realm_name, "component-id": component_id}
  3360. data_raw = self.connection.raw_delete(
  3361. urls_patterns.URL_ADMIN_COMPONENT.format(**params_path)
  3362. )
  3363. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  3364. def get_keys(self):
  3365. """Get keys.
  3366. Return a list of keys, filtered according to query parameters
  3367. KeysMetadataRepresentation
  3368. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_key_resource
  3369. :return: keys list
  3370. :rtype: list
  3371. """
  3372. params_path = {"realm-name": self.connection.realm_name}
  3373. data_raw = self.connection.raw_get(
  3374. urls_patterns.URL_ADMIN_KEYS.format(**params_path), data=None
  3375. )
  3376. return raise_error_from_response(data_raw, KeycloakGetError)
  3377. def get_admin_events(self, query=None):
  3378. """Get Administrative events.
  3379. Return a list of events, filtered according to query parameters
  3380. AdminEvents Representation array
  3381. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getevents
  3382. https://www.keycloak.org/docs-api/22.0.1/rest-api/index.html#_get_adminrealmsrealmadmin_events
  3383. :param query: Additional query parameters
  3384. :type query: dict
  3385. :return: events list
  3386. :rtype: list
  3387. """
  3388. query = query or dict()
  3389. params_path = {"realm-name": self.connection.realm_name}
  3390. data_raw = self.connection.raw_get(
  3391. urls_patterns.URL_ADMIN_ADMIN_EVENTS.format(**params_path), data=None, **query
  3392. )
  3393. return raise_error_from_response(data_raw, KeycloakGetError)
  3394. def get_events(self, query=None):
  3395. """Get events.
  3396. Return a list of events, filtered according to query parameters
  3397. EventRepresentation array
  3398. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_eventrepresentation
  3399. :param query: Additional query parameters
  3400. :type query: dict
  3401. :return: events list
  3402. :rtype: list
  3403. """
  3404. query = query or dict()
  3405. params_path = {"realm-name": self.connection.realm_name}
  3406. data_raw = self.connection.raw_get(
  3407. urls_patterns.URL_ADMIN_USER_EVENTS.format(**params_path), data=None, **query
  3408. )
  3409. return raise_error_from_response(data_raw, KeycloakGetError)
  3410. def set_events(self, payload):
  3411. """Set realm events configuration.
  3412. RealmEventsConfigRepresentation
  3413. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmeventsconfigrepresentation
  3414. :param payload: Payload object for the events configuration
  3415. :type payload: dict
  3416. :return: Http response
  3417. :rtype: bytes
  3418. """
  3419. params_path = {"realm-name": self.connection.realm_name}
  3420. data_raw = self.connection.raw_put(
  3421. urls_patterns.URL_ADMIN_EVENTS_CONFIG.format(**params_path), data=json.dumps(payload)
  3422. )
  3423. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  3424. @deprecation.deprecated(
  3425. deprecated_in="2.13.0",
  3426. removed_in="4.0.0",
  3427. current_version=__version__,
  3428. details="Use the connection.raw_get function instead",
  3429. )
  3430. def raw_get(self, *args, **kwargs):
  3431. """Call connection.raw_get.
  3432. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  3433. and try *get* once more.
  3434. :param args: Additional arguments
  3435. :type args: tuple
  3436. :param kwargs: Additional keyword arguments
  3437. :type kwargs: dict
  3438. :returns: Response
  3439. :rtype: Response
  3440. """
  3441. return self.connection.raw_get(*args, **kwargs)
  3442. @deprecation.deprecated(
  3443. deprecated_in="2.13.0",
  3444. removed_in="4.0.0",
  3445. current_version=__version__,
  3446. details="Use the connection.raw_post function instead",
  3447. )
  3448. def raw_post(self, *args, **kwargs):
  3449. """Call connection.raw_post.
  3450. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  3451. and try *post* once more.
  3452. :param args: Additional arguments
  3453. :type args: tuple
  3454. :param kwargs: Additional keyword arguments
  3455. :type kwargs: dict
  3456. :returns: Response
  3457. :rtype: Response
  3458. """
  3459. return self.connection.raw_post(*args, **kwargs)
  3460. @deprecation.deprecated(
  3461. deprecated_in="2.13.0",
  3462. removed_in="4.0.0",
  3463. current_version=__version__,
  3464. details="Use the connection.raw_put function instead",
  3465. )
  3466. def raw_put(self, *args, **kwargs):
  3467. """Call connection.raw_put.
  3468. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  3469. and try *put* once more.
  3470. :param args: Additional arguments
  3471. :type args: tuple
  3472. :param kwargs: Additional keyword arguments
  3473. :type kwargs: dict
  3474. :returns: Response
  3475. :rtype: Response
  3476. """
  3477. return self.connection.raw_put(*args, **kwargs)
  3478. @deprecation.deprecated(
  3479. deprecated_in="2.13.0",
  3480. removed_in="4.0.0",
  3481. current_version=__version__,
  3482. details="Use the connection.raw_delete function instead",
  3483. )
  3484. def raw_delete(self, *args, **kwargs):
  3485. """Call connection.raw_delete.
  3486. If auto_refresh is set for *delete* and *access_token* is expired,
  3487. it will refresh the token and try *delete* once more.
  3488. :param args: Additional arguments
  3489. :type args: tuple
  3490. :param kwargs: Additional keyword arguments
  3491. :type kwargs: dict
  3492. :returns: Response
  3493. :rtype: Response
  3494. """
  3495. return self.connection.raw_delete(*args, **kwargs)
  3496. @deprecation.deprecated(
  3497. deprecated_in="2.13.0",
  3498. removed_in="4.0.0",
  3499. current_version=__version__,
  3500. details="Use the connection.get_token function instead",
  3501. )
  3502. def get_token(self):
  3503. """Get admin token.
  3504. The admin token is then set in the `token` attribute.
  3505. :returns: token
  3506. :rtype: dict
  3507. """
  3508. return self.connection.get_token()
  3509. @deprecation.deprecated(
  3510. deprecated_in="2.13.0",
  3511. removed_in="4.0.0",
  3512. current_version=__version__,
  3513. details="Use the connection.refresh_token function instead",
  3514. )
  3515. def refresh_token(self):
  3516. """Refresh the token.
  3517. :returns: token
  3518. :rtype: dict
  3519. """
  3520. return self.connection.refresh_token()
  3521. def get_client_all_sessions(self, client_id):
  3522. """Get sessions associated with the client.
  3523. UserSessionRepresentation
  3524. http://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation
  3525. :param client_id: id of client
  3526. :type client_id: str
  3527. :return: UserSessionRepresentation
  3528. :rtype: list
  3529. """
  3530. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3531. data_raw = self.connection.raw_get(
  3532. urls_patterns.URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path)
  3533. )
  3534. return raise_error_from_response(data_raw, KeycloakGetError)
  3535. def get_client_sessions_stats(self):
  3536. """Get current session count for all clients with active sessions.
  3537. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsessionstats
  3538. :return: Dict of clients and session count
  3539. :rtype: dict
  3540. """
  3541. params_path = {"realm-name": self.connection.realm_name}
  3542. data_raw = self.connection.raw_get(
  3543. urls_patterns.URL_ADMIN_CLIENT_SESSION_STATS.format(**params_path)
  3544. )
  3545. return raise_error_from_response(data_raw, KeycloakGetError)
  3546. def get_client_management_permissions(self, client_id):
  3547. """Get management permissions for a client.
  3548. :param client_id: id in ClientRepresentation
  3549. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3550. :type client_id: str
  3551. :return: Keycloak server response
  3552. :rtype: list
  3553. """
  3554. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3555. data_raw = self.connection.raw_get(
  3556. urls_patterns.URL_ADMIN_CLIENT_MANAGEMENT_PERMISSIONS.format(**params_path)
  3557. )
  3558. return raise_error_from_response(data_raw, KeycloakGetError)
  3559. def update_client_management_permissions(self, payload, client_id):
  3560. """Update management permissions for a client.
  3561. ManagementPermissionReference
  3562. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_managementpermissionreference
  3563. Payload example::
  3564. payload={
  3565. "enabled": true
  3566. }
  3567. :param payload: ManagementPermissionReference
  3568. :type payload: dict
  3569. :param client_id: id in ClientRepresentation
  3570. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3571. :type client_id: str
  3572. :return: Keycloak server response
  3573. :rtype: bytes
  3574. """
  3575. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3576. data_raw = self.connection.raw_put(
  3577. urls_patterns.URL_ADMIN_CLIENT_MANAGEMENT_PERMISSIONS.format(**params_path),
  3578. data=json.dumps(payload),
  3579. )
  3580. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[200])
  3581. def get_client_authz_policy_scopes(self, client_id, policy_id):
  3582. """Get scopes for a given policy.
  3583. :param client_id: id in ClientRepresentation
  3584. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3585. :type client_id: str
  3586. :param policy_id: No Document
  3587. :type policy_id: str
  3588. :return: Keycloak server response
  3589. :rtype: list
  3590. """
  3591. params_path = {
  3592. "realm-name": self.connection.realm_name,
  3593. "id": client_id,
  3594. "policy-id": policy_id,
  3595. }
  3596. data_raw = self.connection.raw_get(
  3597. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICY_SCOPES.format(**params_path)
  3598. )
  3599. return raise_error_from_response(data_raw, KeycloakGetError)
  3600. def get_client_authz_policy_resources(self, client_id, policy_id):
  3601. """Get resources for a given policy.
  3602. :param client_id: id in ClientRepresentation
  3603. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3604. :type client_id: str
  3605. :param policy_id: No Document
  3606. :type policy_id: str
  3607. :return: Keycloak server response
  3608. :rtype: list
  3609. """
  3610. params_path = {
  3611. "realm-name": self.connection.realm_name,
  3612. "id": client_id,
  3613. "policy-id": policy_id,
  3614. }
  3615. data_raw = self.connection.raw_get(
  3616. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICY_RESOURCES.format(**params_path)
  3617. )
  3618. return raise_error_from_response(data_raw, KeycloakGetError)
  3619. def get_client_authz_scope_permission(self, client_id, scope_id):
  3620. """Get permissions for a given scope.
  3621. :param client_id: id in ClientRepresentation
  3622. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3623. :type client_id: str
  3624. :param scope_id: No Document
  3625. :type scope_id: str
  3626. :return: Keycloak server response
  3627. :rtype: list
  3628. """
  3629. params_path = {
  3630. "realm-name": self.connection.realm_name,
  3631. "id": client_id,
  3632. "scope-id": scope_id,
  3633. }
  3634. data_raw = self.connection.raw_get(
  3635. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SCOPE_PERMISSION.format(**params_path)
  3636. )
  3637. return raise_error_from_response(data_raw, KeycloakGetError)
  3638. def create_client_authz_scope_permission(self, payload, client_id):
  3639. """Create permissions for a authz scope.
  3640. Payload example::
  3641. payload={
  3642. "name": "My Permission Name",
  3643. "type": "scope",
  3644. "logic": "POSITIVE",
  3645. "decisionStrategy": "UNANIMOUS",
  3646. "resources": [some_resource_id],
  3647. "scopes": [some_scope_id],
  3648. "policies": [some_policy_id],
  3649. }
  3650. :param payload: No Document
  3651. :type payload: dict
  3652. :param client_id: id in ClientRepresentation
  3653. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3654. :type client_id: str
  3655. :return: Keycloak server response
  3656. :rtype: bytes
  3657. """
  3658. params_path = {"realm-name": self.realm_name, "id": client_id}
  3659. data_raw = self.raw_post(
  3660. urls_patterns.URL_ADMIN_ADD_CLIENT_AUTHZ_SCOPE_PERMISSION.format(**params_path),
  3661. data=json.dumps(payload),
  3662. )
  3663. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  3664. def update_client_authz_scope_permission(self, payload, client_id, scope_id):
  3665. """Update permissions for a given scope.
  3666. Payload example::
  3667. payload={
  3668. "id": scope_id,
  3669. "name": "My Permission Name",
  3670. "type": "scope",
  3671. "logic": "POSITIVE",
  3672. "decisionStrategy": "UNANIMOUS",
  3673. "resources": [some_resource_id],
  3674. "scopes": [some_scope_id],
  3675. "policies": [some_policy_id],
  3676. }
  3677. :param payload: No Document
  3678. :type payload: dict
  3679. :param client_id: id in ClientRepresentation
  3680. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3681. :type client_id: str
  3682. :param scope_id: No Document
  3683. :type scope_id: str
  3684. :return: Keycloak server response
  3685. :rtype: bytes
  3686. """
  3687. params_path = {
  3688. "realm-name": self.connection.realm_name,
  3689. "id": client_id,
  3690. "scope-id": scope_id,
  3691. }
  3692. data_raw = self.connection.raw_put(
  3693. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SCOPE_PERMISSION.format(**params_path),
  3694. data=json.dumps(payload),
  3695. )
  3696. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[201])
  3697. def get_client_authz_client_policies(self, client_id):
  3698. """Get policies for a given client.
  3699. :param client_id: id in ClientRepresentation
  3700. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3701. :type client_id: str
  3702. :return: Keycloak server response (RoleRepresentation)
  3703. :rtype: list
  3704. """
  3705. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3706. data_raw = self.connection.raw_get(
  3707. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_CLIENT_POLICY.format(**params_path)
  3708. )
  3709. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  3710. def create_client_authz_client_policy(self, payload, client_id):
  3711. """Create a new policy for a given client.
  3712. Payload example::
  3713. payload={
  3714. "type": "client",
  3715. "logic": "POSITIVE",
  3716. "decisionStrategy": "UNANIMOUS",
  3717. "name": "My Policy",
  3718. "clients": [other_client_id],
  3719. }
  3720. :param payload: No Document
  3721. :type payload: dict
  3722. :param client_id: id in ClientRepresentation
  3723. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  3724. :type client_id: str
  3725. :return: Keycloak server response (RoleRepresentation)
  3726. :rtype: bytes
  3727. """
  3728. params_path = {"realm-name": self.connection.realm_name, "id": client_id}
  3729. data_raw = self.connection.raw_post(
  3730. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_CLIENT_POLICY.format(**params_path),
  3731. data=json.dumps(payload),
  3732. )
  3733. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  3734. def get_composite_client_roles_of_group(self, client_id, group_id, brief_representation=True):
  3735. """Get the composite client roles of the given group for the given client.
  3736. :param client_id: id of the client.
  3737. :type client_id: str
  3738. :param group_id: id of the group.
  3739. :type group_id: str
  3740. :param brief_representation: whether to omit attributes in the response
  3741. :type brief_representation: bool
  3742. :return: the composite client roles of the group (list of RoleRepresentation).
  3743. :rtype: list
  3744. """
  3745. params_path = {
  3746. "realm-name": self.connection.realm_name,
  3747. "id": group_id,
  3748. "client-id": client_id,
  3749. }
  3750. params = {"briefRepresentation": brief_representation}
  3751. data_raw = self.connection.raw_get(
  3752. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES_COMPOSITE.format(**params_path), **params
  3753. )
  3754. return raise_error_from_response(data_raw, KeycloakGetError)
  3755. def get_role_client_level_children(self, client_id, role_id):
  3756. """Get the child roles of which the given composite client role is composed of.
  3757. :param client_id: id of the client.
  3758. :type client_id: str
  3759. :param role_id: id of the role.
  3760. :type role_id: str
  3761. :return: the child roles (list of RoleRepresentation).
  3762. :rtype: list
  3763. """
  3764. params_path = {
  3765. "realm-name": self.connection.realm_name,
  3766. "role-id": role_id,
  3767. "client-id": client_id,
  3768. }
  3769. data_raw = self.connection.raw_get(
  3770. urls_patterns.URL_ADMIN_CLIENT_ROLE_CHILDREN.format(**params_path)
  3771. )
  3772. return raise_error_from_response(data_raw, KeycloakGetError)
  3773. def upload_certificate(self, client_id, certcont):
  3774. """Upload a new certificate for the client.
  3775. :param client_id: id of the client.
  3776. :type client_id: str
  3777. :param certcont: the content of the certificate.
  3778. :type certcont: str
  3779. :return: dictionary {"certificate": "<certcont>"},
  3780. where <certcont> is the content of the uploaded certificate.
  3781. :rtype: dict
  3782. """
  3783. params_path = {
  3784. "realm-name": self.connection.realm_name,
  3785. "id": client_id,
  3786. "attr": "jwt.credential",
  3787. }
  3788. m = MultipartEncoder(fields={"keystoreFormat": "Certificate PEM", "file": certcont})
  3789. new_headers = copy.deepcopy(self.connection.headers)
  3790. new_headers["Content-Type"] = m.content_type
  3791. self.connection.headers = new_headers
  3792. data_raw = self.connection.raw_post(
  3793. urls_patterns.URL_ADMIN_CLIENT_CERT_UPLOAD.format(**params_path),
  3794. data=m,
  3795. headers=new_headers,
  3796. )
  3797. return raise_error_from_response(data_raw, KeycloakPostError)
  3798. def get_required_action_by_alias(self, action_alias):
  3799. """Get a required action by its alias.
  3800. :param action_alias: the alias of the required action.
  3801. :type action_alias: str
  3802. :return: the required action (RequiredActionProviderRepresentation).
  3803. :rtype: dict
  3804. """
  3805. actions = self.get_required_actions()
  3806. for a in actions:
  3807. if a["alias"] == action_alias:
  3808. return a
  3809. return None
  3810. def get_required_actions(self):
  3811. """Get the required actions for the realms.
  3812. :return: the required actions (list of RequiredActionProviderRepresentation).
  3813. :rtype: list
  3814. """
  3815. params_path = {"realm-name": self.connection.realm_name}
  3816. data_raw = self.connection.raw_get(
  3817. urls_patterns.URL_ADMIN_REQUIRED_ACTIONS.format(**params_path)
  3818. )
  3819. return raise_error_from_response(data_raw, KeycloakGetError)
  3820. def update_required_action(self, action_alias, payload):
  3821. """Update a required action.
  3822. :param action_alias: the action alias.
  3823. :type action_alias: str
  3824. :param payload: the new required action (RequiredActionProviderRepresentation).
  3825. :type payload: dict
  3826. :return: empty dictionary.
  3827. :rtype: dict
  3828. """
  3829. if not isinstance(payload, str):
  3830. payload = json.dumps(payload)
  3831. params_path = {"realm-name": self.connection.realm_name, "action-alias": action_alias}
  3832. data_raw = self.connection.raw_put(
  3833. urls_patterns.URL_ADMIN_REQUIRED_ACTIONS_ALIAS.format(**params_path), data=payload
  3834. )
  3835. return raise_error_from_response(data_raw, KeycloakPutError)
  3836. def get_bruteforce_detection_status(self, user_id):
  3837. """Get bruteforce detection status for user.
  3838. :param user_id: User id
  3839. :type user_id: str
  3840. :return: Bruteforce status.
  3841. :rtype: dict
  3842. """
  3843. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  3844. data_raw = self.connection.raw_get(
  3845. urls_patterns.URL_ADMIN_ATTACK_DETECTION_USER.format(**params_path)
  3846. )
  3847. return raise_error_from_response(data_raw, KeycloakGetError)
  3848. def clear_bruteforce_attempts_for_user(self, user_id):
  3849. """Clear bruteforce attempts for user.
  3850. :param user_id: User id
  3851. :type user_id: str
  3852. :return: empty dictionary.
  3853. :rtype: dict
  3854. """
  3855. params_path = {"realm-name": self.connection.realm_name, "id": user_id}
  3856. data_raw = self.connection.raw_delete(
  3857. urls_patterns.URL_ADMIN_ATTACK_DETECTION_USER.format(**params_path)
  3858. )
  3859. return raise_error_from_response(data_raw, KeycloakDeleteError)
  3860. def clear_all_bruteforce_attempts(self):
  3861. """Clear bruteforce attempts for all users in realm.
  3862. :return: empty dictionary.
  3863. :rtype: dict
  3864. """
  3865. params_path = {"realm-name": self.connection.realm_name}
  3866. data_raw = self.connection.raw_delete(
  3867. urls_patterns.URL_ADMIN_ATTACK_DETECTION.format(**params_path)
  3868. )
  3869. return raise_error_from_response(data_raw, KeycloakDeleteError)
  3870. def clear_keys_cache(self):
  3871. """Clear keys cache.
  3872. :return: empty dictionary.
  3873. :rtype: dict
  3874. """
  3875. params_path = {"realm-name": self.connection.realm_name}
  3876. data_raw = self.connection.raw_post(
  3877. urls_patterns.URL_ADMIN_CLEAR_KEYS_CACHE.format(**params_path), data=""
  3878. )
  3879. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  3880. def clear_realm_cache(self):
  3881. """Clear realm cache.
  3882. :return: empty dictionary.
  3883. :rtype: dict
  3884. """
  3885. params_path = {"realm-name": self.connection.realm_name}
  3886. data_raw = self.connection.raw_post(
  3887. urls_patterns.URL_ADMIN_CLEAR_REALM_CACHE.format(**params_path), data=""
  3888. )
  3889. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  3890. def clear_user_cache(self):
  3891. """Clear user cache.
  3892. :return: empty dictionary.
  3893. :rtype: dict
  3894. """
  3895. params_path = {"realm-name": self.connection.realm_name}
  3896. data_raw = self.connection.raw_post(
  3897. urls_patterns.URL_ADMIN_CLEAR_USER_CACHE.format(**params_path), data=""
  3898. )
  3899. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])