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.

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