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.

2639 lines
97 KiB

7 years ago
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 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
3 years ago
3 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from builtins import isinstance
  27. from typing import Iterable
  28. from . import urls_patterns
  29. from .connection import ConnectionManager
  30. from .exceptions import (
  31. KeycloakDeleteError,
  32. KeycloakGetError,
  33. KeycloakPostError,
  34. KeycloakPutError,
  35. raise_error_from_response,
  36. )
  37. from .keycloak_openid import KeycloakOpenID
  38. class KeycloakAdmin:
  39. """
  40. Keycloak Admin client.
  41. :param server_url: Keycloak server url
  42. :param username: admin username
  43. :param password: admin password
  44. :param totp: Time based OTP
  45. :param realm_name: realm name
  46. :param client_id: client id
  47. :param verify: True if want check connection SSL
  48. :param client_secret_key: client secret key
  49. (optional, required only for access type confidential)
  50. :param custom_headers: dict of custom header to pass to each HTML request
  51. :param user_realm_name: The realm name of the user, if different from realm_name
  52. :param auto_refresh_token: list of methods that allows automatic token refresh.
  53. Ex: ['get', 'put', 'post', 'delete']
  54. """
  55. PAGE_SIZE = 100
  56. _server_url = None
  57. _username = None
  58. _password = None
  59. _totp = None
  60. _realm_name = None
  61. _client_id = None
  62. _verify = None
  63. _client_secret_key = None
  64. _auto_refresh_token = None
  65. _connection = None
  66. _token = None
  67. _custom_headers = None
  68. _user_realm_name = None
  69. def __init__(
  70. self,
  71. server_url,
  72. username=None,
  73. password=None,
  74. totp=None,
  75. realm_name="master",
  76. client_id="admin-cli",
  77. verify=True,
  78. client_secret_key=None,
  79. custom_headers=None,
  80. user_realm_name=None,
  81. auto_refresh_token=None,
  82. ):
  83. self.server_url = server_url
  84. self.username = username
  85. self.password = password
  86. self.totp = totp
  87. self.realm_name = realm_name
  88. self.client_id = client_id
  89. self.verify = verify
  90. self.client_secret_key = client_secret_key
  91. self.auto_refresh_token = auto_refresh_token or []
  92. self.user_realm_name = user_realm_name
  93. self.custom_headers = custom_headers
  94. # Get token Admin
  95. self.get_token()
  96. @property
  97. def server_url(self):
  98. return self._server_url
  99. @server_url.setter
  100. def server_url(self, value):
  101. self._server_url = value
  102. @property
  103. def realm_name(self):
  104. return self._realm_name
  105. @realm_name.setter
  106. def realm_name(self, value):
  107. self._realm_name = value
  108. @property
  109. def connection(self):
  110. return self._connection
  111. @connection.setter
  112. def connection(self, value):
  113. self._connection = value
  114. @property
  115. def client_id(self):
  116. return self._client_id
  117. @client_id.setter
  118. def client_id(self, value):
  119. self._client_id = value
  120. @property
  121. def client_secret_key(self):
  122. return self._client_secret_key
  123. @client_secret_key.setter
  124. def client_secret_key(self, value):
  125. self._client_secret_key = value
  126. @property
  127. def verify(self):
  128. return self._verify
  129. @verify.setter
  130. def verify(self, value):
  131. self._verify = value
  132. @property
  133. def username(self):
  134. return self._username
  135. @username.setter
  136. def username(self, value):
  137. self._username = value
  138. @property
  139. def password(self):
  140. return self._password
  141. @password.setter
  142. def password(self, value):
  143. self._password = value
  144. @property
  145. def totp(self):
  146. return self._totp
  147. @totp.setter
  148. def totp(self, value):
  149. self._totp = value
  150. @property
  151. def token(self):
  152. return self._token
  153. @token.setter
  154. def token(self, value):
  155. self._token = value
  156. @property
  157. def auto_refresh_token(self):
  158. return self._auto_refresh_token
  159. @property
  160. def user_realm_name(self):
  161. return self._user_realm_name
  162. @user_realm_name.setter
  163. def user_realm_name(self, value):
  164. self._user_realm_name = value
  165. @property
  166. def custom_headers(self):
  167. return self._custom_headers
  168. @custom_headers.setter
  169. def custom_headers(self, value):
  170. self._custom_headers = value
  171. @auto_refresh_token.setter
  172. def auto_refresh_token(self, value):
  173. allowed_methods = {"get", "post", "put", "delete"}
  174. if not isinstance(value, Iterable):
  175. raise TypeError(
  176. "Expected a list of strings among {allowed}".format(allowed=allowed_methods)
  177. )
  178. if not all(method in allowed_methods for method in value):
  179. raise TypeError(
  180. "Unexpected method in auto_refresh_token, accepted methods are {allowed}".format(
  181. allowed=allowed_methods
  182. )
  183. )
  184. self._auto_refresh_token = value
  185. def __fetch_all(self, url, query=None):
  186. """Wrapper function to paginate GET requests
  187. :param url: The url on which the query is executed
  188. :param query: Existing query parameters (optional)
  189. :return: Combined results of paginated queries
  190. """
  191. results = []
  192. # initalize query if it was called with None
  193. if not query:
  194. query = {}
  195. page = 0
  196. query["max"] = self.PAGE_SIZE
  197. # fetch until we can
  198. while True:
  199. query["first"] = page * self.PAGE_SIZE
  200. partial_results = raise_error_from_response(
  201. self.raw_get(url, **query), KeycloakGetError
  202. )
  203. if not partial_results:
  204. break
  205. results.extend(partial_results)
  206. if len(partial_results) < query["max"]:
  207. break
  208. page += 1
  209. return results
  210. def __fetch_paginated(self, url, query=None):
  211. query = query or {}
  212. return raise_error_from_response(self.raw_get(url, **query), KeycloakGetError)
  213. def import_realm(self, payload):
  214. """
  215. Import a new realm from a RealmRepresentation. Realm name must be unique.
  216. RealmRepresentation
  217. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  218. :param payload: RealmRepresentation
  219. :return: RealmRepresentation
  220. """
  221. data_raw = self.raw_post(urls_patterns.URL_ADMIN_REALMS, data=json.dumps(payload))
  222. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  223. def export_realm(self, export_clients=False, export_groups_and_role=False):
  224. """
  225. Export the realm configurations in the json format
  226. RealmRepresentation
  227. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_partialexport
  228. :param export-clients: Skip if not want to export realm clients
  229. :param export-groups-and-roles: Skip if not want to export realm groups and roles
  230. :return: realm configurations JSON
  231. """
  232. params_path = {
  233. "realm-name": self.realm_name,
  234. "export-clients": export_clients,
  235. "export-groups-and-roles": export_groups_and_role,
  236. }
  237. data_raw = self.raw_post(
  238. urls_patterns.URL_ADMIN_REALM_EXPORT.format(**params_path), data=""
  239. )
  240. return raise_error_from_response(data_raw, KeycloakPostError)
  241. def get_realms(self):
  242. """
  243. Lists all realms in Keycloak deployment
  244. :return: realms list
  245. """
  246. data_raw = self.raw_get(urls_patterns.URL_ADMIN_REALMS)
  247. return raise_error_from_response(data_raw, KeycloakGetError)
  248. def get_realm(self, realm_name):
  249. """
  250. Get a specific realm.
  251. RealmRepresentation:
  252. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  253. :param realm_name: Realm name (not the realm id)
  254. :return: RealmRepresentation
  255. """
  256. params_path = {"realm-name": realm_name}
  257. data_raw = self.raw_get(urls_patterns.URL_ADMIN_REALM.format(**params_path))
  258. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  259. def create_realm(self, payload, skip_exists=False):
  260. """
  261. Create a realm
  262. RealmRepresentation:
  263. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  264. :param payload: RealmRepresentation
  265. :param skip_exists: Skip if Realm already exist.
  266. :return: Keycloak server response (RealmRepresentation)
  267. """
  268. data_raw = self.raw_post(urls_patterns.URL_ADMIN_REALMS, data=json.dumps(payload))
  269. return raise_error_from_response(
  270. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  271. )
  272. def update_realm(self, realm_name, payload):
  273. """
  274. Update a realm. This wil only update top level attributes and will ignore any user,
  275. role, or client information in the payload.
  276. RealmRepresentation:
  277. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation
  278. :param realm_name: Realm name (not the realm id)
  279. :param payload: RealmRepresentation
  280. :return: Http response
  281. """
  282. params_path = {"realm-name": realm_name}
  283. data_raw = self.raw_put(
  284. urls_patterns.URL_ADMIN_REALM.format(**params_path), data=json.dumps(payload)
  285. )
  286. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  287. def delete_realm(self, realm_name):
  288. """
  289. Delete a realm
  290. :param realm_name: Realm name (not the realm id)
  291. :return: Http response
  292. """
  293. params_path = {"realm-name": realm_name}
  294. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_REALM.format(**params_path))
  295. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  296. def get_users(self, query=None):
  297. """
  298. Return a list of users, filtered according to query parameters
  299. UserRepresentation
  300. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  301. :param query: Query parameters (optional)
  302. :return: users list
  303. """
  304. query = query or {}
  305. params_path = {"realm-name": self.realm_name}
  306. url = urls_patterns.URL_ADMIN_USERS.format(**params_path)
  307. if "first" in query or "max" in query:
  308. return self.__fetch_paginated(url, query)
  309. return self.__fetch_all(url, query)
  310. def create_idp(self, payload):
  311. """
  312. Create an ID Provider,
  313. IdentityProviderRepresentation
  314. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation
  315. :param: payload: IdentityProviderRepresentation
  316. """
  317. params_path = {"realm-name": self.realm_name}
  318. data_raw = self.raw_post(
  319. urls_patterns.URL_ADMIN_IDPS.format(**params_path), data=json.dumps(payload)
  320. )
  321. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  322. def add_mapper_to_idp(self, idp_alias, payload):
  323. """
  324. Create an ID Provider,
  325. IdentityProviderRepresentation
  326. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityprovidermapperrepresentation
  327. :param: idp_alias: alias for Idp to add mapper in
  328. :param: payload: IdentityProviderMapperRepresentation
  329. """
  330. params_path = {"realm-name": self.realm_name, "idp-alias": idp_alias}
  331. data_raw = self.raw_post(
  332. urls_patterns.URL_ADMIN_IDP_MAPPERS.format(**params_path), data=json.dumps(payload)
  333. )
  334. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  335. def get_idps(self):
  336. """
  337. Returns a list of ID Providers,
  338. IdentityProviderRepresentation
  339. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation
  340. :return: array IdentityProviderRepresentation
  341. """
  342. params_path = {"realm-name": self.realm_name}
  343. data_raw = self.raw_get(urls_patterns.URL_ADMIN_IDPS.format(**params_path))
  344. return raise_error_from_response(data_raw, KeycloakGetError)
  345. def delete_idp(self, idp_alias):
  346. """
  347. Deletes ID Provider,
  348. :param: idp_alias: idp alias name
  349. """
  350. params_path = {"realm-name": self.realm_name, "alias": idp_alias}
  351. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_IDP.format(**params_path))
  352. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  353. def create_user(self, payload, exist_ok=False):
  354. """
  355. Create a new user. Username must be unique
  356. UserRepresentation
  357. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  358. :param payload: UserRepresentation
  359. :param exist_ok: If False, raise KeycloakGetError if username already exists.
  360. Otherwise, return existing user ID.
  361. :return: UserRepresentation
  362. """
  363. params_path = {"realm-name": self.realm_name}
  364. if exist_ok:
  365. exists = self.get_user_id(username=payload["username"])
  366. if exists is not None:
  367. return str(exists)
  368. data_raw = self.raw_post(
  369. urls_patterns.URL_ADMIN_USERS.format(**params_path), data=json.dumps(payload)
  370. )
  371. raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  372. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  373. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  374. def users_count(self):
  375. """
  376. User counter
  377. :return: counter
  378. """
  379. params_path = {"realm-name": self.realm_name}
  380. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USERS_COUNT.format(**params_path))
  381. return raise_error_from_response(data_raw, KeycloakGetError)
  382. def get_user_id(self, username):
  383. """
  384. Get internal keycloak user id from username
  385. This is required for further actions against this user.
  386. UserRepresentation
  387. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  388. :param username: id in UserRepresentation
  389. :return: user_id
  390. """
  391. lower_user_name = username.lower()
  392. users = self.get_users(query={"search": lower_user_name})
  393. return next((user["id"] for user in users if user["username"] == lower_user_name), None)
  394. def get_user(self, user_id):
  395. """
  396. Get representation of the user
  397. :param user_id: User id
  398. UserRepresentation
  399. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation
  400. :return: UserRepresentation
  401. """
  402. params_path = {"realm-name": self.realm_name, "id": user_id}
  403. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USER.format(**params_path))
  404. return raise_error_from_response(data_raw, KeycloakGetError)
  405. def get_user_groups(self, user_id):
  406. """
  407. Returns a list of groups of which the user is a member
  408. :param user_id: User id
  409. :return: user groups list
  410. """
  411. params_path = {"realm-name": self.realm_name, "id": user_id}
  412. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USER_GROUPS.format(**params_path))
  413. return raise_error_from_response(data_raw, KeycloakGetError)
  414. def update_user(self, user_id, payload):
  415. """
  416. Update the user
  417. :param user_id: User id
  418. :param payload: UserRepresentation
  419. :return: Http response
  420. """
  421. params_path = {"realm-name": self.realm_name, "id": user_id}
  422. data_raw = self.raw_put(
  423. urls_patterns.URL_ADMIN_USER.format(**params_path), data=json.dumps(payload)
  424. )
  425. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  426. def delete_user(self, user_id):
  427. """
  428. Delete the user
  429. :param user_id: User id
  430. :return: Http response
  431. """
  432. params_path = {"realm-name": self.realm_name, "id": user_id}
  433. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_USER.format(**params_path))
  434. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  435. def set_user_password(self, user_id, password, temporary=True):
  436. """
  437. Set up a password for the user. If temporary is True, the user will have to reset
  438. the temporary password next time they log in.
  439. https://www.keycloak.org/docs-api/18.0/rest-api/#_users_resource
  440. https://www.keycloak.org/docs-api/18.0/rest-api/#_credentialrepresentation
  441. :param user_id: User id
  442. :param password: New password
  443. :param temporary: True if password is temporary
  444. :return:
  445. """
  446. payload = {"type": "password", "temporary": temporary, "value": password}
  447. params_path = {"realm-name": self.realm_name, "id": user_id}
  448. data_raw = self.raw_put(
  449. urls_patterns.URL_ADMIN_RESET_PASSWORD.format(**params_path), data=json.dumps(payload)
  450. )
  451. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  452. def get_credentials(self, user_id):
  453. """
  454. Returns a list of credential belonging to the user.
  455. CredentialRepresentation
  456. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation
  457. :param: user_id: user id
  458. :return: Keycloak server response (CredentialRepresentation)
  459. """
  460. params_path = {"realm-name": self.realm_name, "id": user_id}
  461. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USER_CREDENTIALS.format(**params_path))
  462. return raise_error_from_response(data_raw, KeycloakGetError)
  463. def delete_credential(self, user_id, credential_id):
  464. """
  465. Delete credential of the user.
  466. CredentialRepresentation
  467. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation
  468. :param: user_id: user id
  469. :param: credential_id: credential id
  470. :return: Keycloak server response (ClientRepresentation)
  471. """
  472. params_path = {
  473. "realm-name": self.realm_name,
  474. "id": user_id,
  475. "credential_id": credential_id,
  476. }
  477. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_USER_CREDENTIAL.format(**params_path))
  478. return raise_error_from_response(data_raw, KeycloakDeleteError)
  479. def user_logout(self, user_id):
  480. """
  481. Logs out user.
  482. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_logout
  483. :param user_id: User id
  484. :return:
  485. """
  486. params_path = {"realm-name": self.realm_name, "id": user_id}
  487. data_raw = self.raw_post(
  488. urls_patterns.URL_ADMIN_USER_LOGOUT.format(**params_path), data=""
  489. )
  490. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  491. def user_consents(self, user_id):
  492. """
  493. Get consents granted by the user
  494. UserConsentRepresentation
  495. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userconsentrepresentation
  496. :param user_id: User id
  497. :return: List of UserConsentRepresentations
  498. """
  499. params_path = {"realm-name": self.realm_name, "id": user_id}
  500. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USER_CONSENTS.format(**params_path))
  501. return raise_error_from_response(data_raw, KeycloakGetError)
  502. def get_user_social_logins(self, user_id):
  503. """
  504. Returns a list of federated identities/social logins of which the user has been associated
  505. with
  506. :param user_id: User id
  507. :return: federated identities list
  508. """
  509. params_path = {"realm-name": self.realm_name, "id": user_id}
  510. data_raw = self.raw_get(
  511. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path)
  512. )
  513. return raise_error_from_response(data_raw, KeycloakGetError)
  514. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  515. """
  516. Add a federated identity / social login provider to the user
  517. :param user_id: User id
  518. :param provider_id: Social login provider id
  519. :param provider_userid: userid specified by the provider
  520. :param provider_username: username specified by the provider
  521. :return:
  522. """
  523. payload = {
  524. "identityProvider": provider_id,
  525. "userId": provider_userid,
  526. "userName": provider_username,
  527. }
  528. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  529. data_raw = self.raw_post(
  530. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path),
  531. data=json.dumps(payload),
  532. )
  533. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201, 204])
  534. def delete_user_social_login(self, user_id, provider_id):
  535. """
  536. Delete a federated identity / social login provider from the user
  537. :param user_id: User id
  538. :param provider_id: Social login provider id
  539. :return:
  540. """
  541. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  542. data_raw = self.raw_delete(
  543. urls_patterns.URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path)
  544. )
  545. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  546. def send_update_account(
  547. self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None
  548. ):
  549. """
  550. Send an update account email to the user. An email contains a
  551. link the user can click to perform a set of required actions.
  552. :param user_id: User id
  553. :param payload: A list of actions for the user to complete
  554. :param client_id: Client id (optional)
  555. :param lifespan: Number of seconds after which the generated token expires (optional)
  556. :param redirect_uri: The redirect uri (optional)
  557. :return:
  558. """
  559. params_path = {"realm-name": self.realm_name, "id": user_id}
  560. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  561. data_raw = self.raw_put(
  562. urls_patterns.URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  563. data=json.dumps(payload),
  564. **params_query
  565. )
  566. return raise_error_from_response(data_raw, KeycloakPutError)
  567. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  568. """
  569. Send a update account email to the user An email contains a
  570. link the user can click to perform a set of required actions.
  571. :param user_id: User id
  572. :param client_id: Client id (optional)
  573. :param redirect_uri: Redirect uri (optional)
  574. :return:
  575. """
  576. params_path = {"realm-name": self.realm_name, "id": user_id}
  577. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  578. data_raw = self.raw_put(
  579. urls_patterns.URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  580. data={},
  581. **params_query
  582. )
  583. return raise_error_from_response(data_raw, KeycloakPutError)
  584. def get_sessions(self, user_id):
  585. """
  586. Get sessions associated with the user
  587. :param user_id: id of user
  588. UserSessionRepresentation
  589. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation
  590. :return: UserSessionRepresentation
  591. """
  592. params_path = {"realm-name": self.realm_name, "id": user_id}
  593. data_raw = self.raw_get(urls_patterns.URL_ADMIN_GET_SESSIONS.format(**params_path))
  594. return raise_error_from_response(data_raw, KeycloakGetError)
  595. def get_server_info(self):
  596. """
  597. Get themes, social providers, auth providers, and event listeners available on this server
  598. ServerInfoRepresentation
  599. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation
  600. :return: ServerInfoRepresentation
  601. """
  602. data_raw = self.raw_get(urls_patterns.URL_ADMIN_SERVER_INFO)
  603. return raise_error_from_response(data_raw, KeycloakGetError)
  604. def get_groups(self, query=None):
  605. """
  606. Returns a list of groups belonging to the realm
  607. GroupRepresentation
  608. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  609. :return: array GroupRepresentation
  610. """
  611. query = query or {}
  612. params_path = {"realm-name": self.realm_name}
  613. url = urls_patterns.URL_ADMIN_GROUPS.format(**params_path)
  614. if "first" in query or "max" in query:
  615. return self.__fetch_paginated(url, query)
  616. return self.__fetch_all(url, query)
  617. def get_group(self, group_id):
  618. """
  619. Get group by id. Returns full group details
  620. GroupRepresentation
  621. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  622. :param group_id: The group id
  623. :return: Keycloak server response (GroupRepresentation)
  624. """
  625. params_path = {"realm-name": self.realm_name, "id": group_id}
  626. data_raw = self.raw_get(urls_patterns.URL_ADMIN_GROUP.format(**params_path))
  627. return raise_error_from_response(data_raw, KeycloakGetError)
  628. def get_subgroups(self, group, path):
  629. """
  630. Utility function to iterate through nested group structures
  631. GroupRepresentation
  632. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  633. :param name: group (GroupRepresentation)
  634. :param path: group path (string)
  635. :return: Keycloak server response (GroupRepresentation)
  636. """
  637. for subgroup in group["subGroups"]:
  638. if subgroup["path"] == path:
  639. return subgroup
  640. elif subgroup["subGroups"]:
  641. for subgroup in group["subGroups"]:
  642. result = self.get_subgroups(subgroup, path)
  643. if result:
  644. return result
  645. # went through the tree without hits
  646. return None
  647. def get_group_members(self, group_id, query=None):
  648. """
  649. Get members by group id. Returns group members
  650. GroupRepresentation
  651. https://www.keycloak.org/docs-api/18.0/rest-api/#_userrepresentation
  652. :param group_id: The group id
  653. :param query: Additional query parameters
  654. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getmembers)
  655. :return: Keycloak server response (UserRepresentation)
  656. """
  657. query = query or {}
  658. params_path = {"realm-name": self.realm_name, "id": group_id}
  659. url = urls_patterns.URL_ADMIN_GROUP_MEMBERS.format(**params_path)
  660. if "first" in query or "max" in query:
  661. return self.__fetch_paginated(url, query)
  662. return self.__fetch_all(url, query)
  663. def get_group_by_path(self, path, search_in_subgroups=False):
  664. """
  665. Get group id based on name or path.
  666. A straight name or path match with a top-level group will return first.
  667. Subgroups are traversed, the first to match path (or name with path) is returned.
  668. GroupRepresentation
  669. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  670. :param path: group path
  671. :param search_in_subgroups: True if want search in the subgroups
  672. :return: Keycloak server response (GroupRepresentation)
  673. """
  674. groups = self.get_groups()
  675. # TODO: Review this code is necessary
  676. for group in groups:
  677. if group["path"] == path:
  678. return group
  679. elif search_in_subgroups and group["subGroups"]:
  680. for group in group["subGroups"]:
  681. if group["path"] == path:
  682. return group
  683. res = self.get_subgroups(group, path)
  684. if res is not None:
  685. return res
  686. return None
  687. def create_group(self, payload, parent=None, skip_exists=False):
  688. """
  689. Creates a group in the Realm
  690. :param payload: GroupRepresentation
  691. :param parent: parent group's id. Required to create a sub-group.
  692. :param skip_exists: If true then do not raise an error if it already exists
  693. GroupRepresentation
  694. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  695. :return: Group id for newly created group or None for an existing group
  696. """
  697. if parent is None:
  698. params_path = {"realm-name": self.realm_name}
  699. data_raw = self.raw_post(
  700. urls_patterns.URL_ADMIN_GROUPS.format(**params_path), data=json.dumps(payload)
  701. )
  702. else:
  703. params_path = {"realm-name": self.realm_name, "id": parent}
  704. data_raw = self.raw_post(
  705. urls_patterns.URL_ADMIN_GROUP_CHILD.format(**params_path), data=json.dumps(payload)
  706. )
  707. raise_error_from_response(
  708. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  709. )
  710. try:
  711. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  712. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  713. except KeyError:
  714. return
  715. def update_group(self, group_id, payload):
  716. """
  717. Update group, ignores subgroups.
  718. :param group_id: id of group
  719. :param payload: GroupRepresentation with updated information.
  720. GroupRepresentation
  721. https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation
  722. :return: Http response
  723. """
  724. params_path = {"realm-name": self.realm_name, "id": group_id}
  725. data_raw = self.raw_put(
  726. urls_patterns.URL_ADMIN_GROUP.format(**params_path), data=json.dumps(payload)
  727. )
  728. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  729. def group_set_permissions(self, group_id, enabled=True):
  730. """
  731. Enable/Disable permissions for a group. Cannot delete group if disabled
  732. :param group_id: id of group
  733. :param enabled: boolean
  734. :return: Keycloak server response
  735. """
  736. params_path = {"realm-name": self.realm_name, "id": group_id}
  737. data_raw = self.raw_put(
  738. urls_patterns.URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  739. data=json.dumps({"enabled": enabled}),
  740. )
  741. return raise_error_from_response(data_raw, KeycloakPutError)
  742. def group_user_add(self, user_id, group_id):
  743. """
  744. Add user to group (user_id and group_id)
  745. :param user_id: id of user
  746. :param group_id: id of group to add to
  747. :return: Keycloak server response
  748. """
  749. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  750. data_raw = self.raw_put(
  751. urls_patterns.URL_ADMIN_USER_GROUP.format(**params_path), data=None
  752. )
  753. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  754. def group_user_remove(self, user_id, group_id):
  755. """
  756. Remove user from group (user_id and group_id)
  757. :param user_id: id of user
  758. :param group_id: id of group to remove from
  759. :return: Keycloak server response
  760. """
  761. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  762. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_USER_GROUP.format(**params_path))
  763. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  764. def delete_group(self, group_id):
  765. """
  766. Deletes a group in the Realm
  767. :param group_id: id of group to delete
  768. :return: Keycloak server response
  769. """
  770. params_path = {"realm-name": self.realm_name, "id": group_id}
  771. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_GROUP.format(**params_path))
  772. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  773. def get_clients(self):
  774. """
  775. Returns a list of clients belonging to the realm
  776. ClientRepresentation
  777. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  778. :return: Keycloak server response (ClientRepresentation)
  779. """
  780. params_path = {"realm-name": self.realm_name}
  781. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENTS.format(**params_path))
  782. return raise_error_from_response(data_raw, KeycloakGetError)
  783. def get_client(self, client_id):
  784. """
  785. Get representation of the client
  786. ClientRepresentation
  787. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  788. :param client_id: id of client (not client-id)
  789. :return: Keycloak server response (ClientRepresentation)
  790. """
  791. params_path = {"realm-name": self.realm_name, "id": client_id}
  792. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT.format(**params_path))
  793. return raise_error_from_response(data_raw, KeycloakGetError)
  794. def get_client_id(self, client_name):
  795. """
  796. Get internal keycloak client id from client-id.
  797. This is required for further actions against this client.
  798. :param client_name: name in ClientRepresentation
  799. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  800. :return: client_id (uuid as string)
  801. """
  802. clients = self.get_clients()
  803. for client in clients:
  804. if client_name == client.get("name") or client_name == client.get("clientId"):
  805. return client["id"]
  806. return None
  807. def get_client_authz_settings(self, client_id):
  808. """
  809. Get authorization json from client.
  810. :param client_id: id in ClientRepresentation
  811. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  812. :return: Keycloak server response
  813. """
  814. params_path = {"realm-name": self.realm_name, "id": client_id}
  815. data_raw = self.raw_get(
  816. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path)
  817. )
  818. return raise_error_from_response(data_raw, KeycloakGetError)
  819. def create_client_authz_resource(self, client_id, payload, skip_exists=False):
  820. """
  821. Create resources of client.
  822. :param client_id: id in ClientRepresentation
  823. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  824. :param payload: ResourceRepresentation
  825. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_resourcerepresentation
  826. :return: Keycloak server response
  827. """
  828. params_path = {"realm-name": self.realm_name, "id": client_id}
  829. data_raw = self.raw_post(
  830. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path),
  831. data=json.dumps(payload),
  832. )
  833. return raise_error_from_response(
  834. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  835. )
  836. def get_client_authz_resources(self, client_id):
  837. """
  838. Get resources from client.
  839. :param client_id: id in ClientRepresentation
  840. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  841. :return: Keycloak server response
  842. """
  843. params_path = {"realm-name": self.realm_name, "id": client_id}
  844. data_raw = self.raw_get(
  845. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path)
  846. )
  847. return raise_error_from_response(data_raw, KeycloakGetError)
  848. def create_client_authz_role_based_policy(self, client_id, payload, skip_exists=False):
  849. """
  850. Create role-based policy of client.
  851. :param client_id: id in ClientRepresentation
  852. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  853. :param payload: No Document
  854. :return: Keycloak server response
  855. Payload example::
  856. payload={
  857. "type": "role",
  858. "logic": "POSITIVE",
  859. "decisionStrategy": "UNANIMOUS",
  860. "name": "Policy-1",
  861. "roles": [
  862. {
  863. "id": id
  864. }
  865. ]
  866. }
  867. """
  868. params_path = {"realm-name": self.realm_name, "id": client_id}
  869. data_raw = self.raw_post(
  870. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_POLICY.format(**params_path),
  871. data=json.dumps(payload),
  872. )
  873. return raise_error_from_response(
  874. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  875. )
  876. def create_client_authz_resource_based_permission(self, client_id, payload, skip_exists=False):
  877. """
  878. Create resource-based permission of client.
  879. :param client_id: id in ClientRepresentation
  880. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  881. :param payload: PolicyRepresentation
  882. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_policyrepresentation
  883. :return: Keycloak server response
  884. Payload example::
  885. payload={
  886. "type": "resource",
  887. "logic": "POSITIVE",
  888. "decisionStrategy": "UNANIMOUS",
  889. "name": "Permission-Name",
  890. "resources": [
  891. resource_id
  892. ],
  893. "policies": [
  894. policy_id
  895. ]
  896. """
  897. params_path = {"realm-name": self.realm_name, "id": client_id}
  898. data_raw = self.raw_post(
  899. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_RESOURCE_BASED_PERMISSION.format(**params_path),
  900. data=json.dumps(payload),
  901. )
  902. return raise_error_from_response(
  903. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  904. )
  905. def get_client_authz_scopes(self, client_id):
  906. """
  907. Get scopes from client.
  908. :param client_id: id in ClientRepresentation
  909. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  910. :return: Keycloak server response
  911. """
  912. params_path = {"realm-name": self.realm_name, "id": client_id}
  913. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_AUTHZ_SCOPES.format(**params_path))
  914. return raise_error_from_response(data_raw, KeycloakGetError)
  915. def get_client_authz_permissions(self, client_id):
  916. """
  917. Get permissions from client.
  918. :param client_id: id in ClientRepresentation
  919. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  920. :return: Keycloak server response
  921. """
  922. params_path = {"realm-name": self.realm_name, "id": client_id}
  923. data_raw = self.raw_get(
  924. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_PERMISSIONS.format(**params_path)
  925. )
  926. return raise_error_from_response(data_raw, KeycloakGetError)
  927. def get_client_authz_policies(self, client_id):
  928. """
  929. Get policies from client.
  930. :param client_id: id in ClientRepresentation
  931. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  932. :return: Keycloak server response
  933. """
  934. params_path = {"realm-name": self.realm_name, "id": client_id}
  935. data_raw = self.raw_get(
  936. urls_patterns.URL_ADMIN_CLIENT_AUTHZ_POLICIES.format(**params_path)
  937. )
  938. return raise_error_from_response(data_raw, KeycloakGetError)
  939. def get_client_service_account_user(self, client_id):
  940. """
  941. Get service account user from client.
  942. :param client_id: id in ClientRepresentation
  943. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  944. :return: UserRepresentation
  945. """
  946. params_path = {"realm-name": self.realm_name, "id": client_id}
  947. data_raw = self.raw_get(
  948. urls_patterns.URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path)
  949. )
  950. return raise_error_from_response(data_raw, KeycloakGetError)
  951. def create_client(self, payload, skip_exists=False):
  952. """
  953. Create a client
  954. ClientRepresentation:
  955. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  956. :param skip_exists: If true then do not raise an error if client already exists
  957. :param payload: ClientRepresentation
  958. :return: Client ID
  959. """
  960. if skip_exists:
  961. client_id = self.get_client_id(client_name=payload["name"])
  962. if client_id is not None:
  963. return client_id
  964. params_path = {"realm-name": self.realm_name}
  965. data_raw = self.raw_post(
  966. urls_patterns.URL_ADMIN_CLIENTS.format(**params_path), data=json.dumps(payload)
  967. )
  968. raise_error_from_response(
  969. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  970. )
  971. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  972. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  973. def update_client(self, client_id, payload):
  974. """
  975. Update a client
  976. :param client_id: Client id
  977. :param payload: ClientRepresentation
  978. :return: Http response
  979. """
  980. params_path = {"realm-name": self.realm_name, "id": client_id}
  981. data_raw = self.raw_put(
  982. urls_patterns.URL_ADMIN_CLIENT.format(**params_path), data=json.dumps(payload)
  983. )
  984. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  985. def delete_client(self, client_id):
  986. """
  987. Get representation of the client
  988. ClientRepresentation
  989. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  990. :param client_id: keycloak client id (not oauth client-id)
  991. :return: Keycloak server response (ClientRepresentation)
  992. """
  993. params_path = {"realm-name": self.realm_name, "id": client_id}
  994. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_CLIENT.format(**params_path))
  995. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  996. def get_client_installation_provider(self, client_id, provider_id):
  997. """
  998. Get content for given installation provider
  999. Related documentation:
  1000. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource
  1001. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  1002. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation
  1003. :param client_id: Client id
  1004. :param provider_id: provider id to specify response format
  1005. """
  1006. params_path = {"realm-name": self.realm_name, "id": client_id, "provider-id": provider_id}
  1007. data_raw = self.raw_get(
  1008. urls_patterns.URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path)
  1009. )
  1010. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  1011. def get_realm_roles(self):
  1012. """
  1013. Get all roles for the realm or client
  1014. RoleRepresentation
  1015. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1016. :return: Keycloak server response (RoleRepresentation)
  1017. """
  1018. params_path = {"realm-name": self.realm_name}
  1019. data_raw = self.raw_get(urls_patterns.URL_ADMIN_REALM_ROLES.format(**params_path))
  1020. return raise_error_from_response(data_raw, KeycloakGetError)
  1021. def get_realm_role_members(self, role_name, query=None):
  1022. """
  1023. Get role members of realm by role name.
  1024. :param role_name: Name of the role.
  1025. :param query: Additional Query parameters
  1026. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_roles_resource)
  1027. :return: Keycloak Server Response (UserRepresentation)
  1028. """
  1029. query = query or dict()
  1030. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1031. return self.__fetch_all(
  1032. urls_patterns.URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query
  1033. )
  1034. def get_client_roles(self, client_id):
  1035. """
  1036. Get all roles for the client
  1037. :param client_id: id of client (not client-id)
  1038. RoleRepresentation
  1039. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1040. :return: Keycloak server response (RoleRepresentation)
  1041. """
  1042. params_path = {"realm-name": self.realm_name, "id": client_id}
  1043. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_ROLES.format(**params_path))
  1044. return raise_error_from_response(data_raw, KeycloakGetError)
  1045. def get_client_role(self, client_id, role_name):
  1046. """
  1047. Get client role id by name
  1048. This is required for further actions with this role.
  1049. :param client_id: id of client (not client-id)
  1050. :param role_name: roles name (not id!)
  1051. RoleRepresentation
  1052. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1053. :return: role_id
  1054. """
  1055. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  1056. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path))
  1057. return raise_error_from_response(data_raw, KeycloakGetError)
  1058. def get_client_role_id(self, client_id, role_name):
  1059. """
  1060. Warning: Deprecated
  1061. Get client role id by name
  1062. This is required for further actions with this role.
  1063. :param client_id: id of client (not client-id)
  1064. :param role_name: roles name (not id!)
  1065. RoleRepresentation
  1066. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1067. :return: role_id
  1068. """
  1069. role = self.get_client_role(client_id, role_name)
  1070. return role.get("id")
  1071. def create_client_role(self, client_role_id, payload, skip_exists=False):
  1072. """
  1073. Create a client role
  1074. RoleRepresentation
  1075. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1076. :param client_role_id: id of client (not client-id)
  1077. :param payload: RoleRepresentation
  1078. :param skip_exists: If true then do not raise an error if client role already exists
  1079. :return: Client role name
  1080. """
  1081. if skip_exists:
  1082. res = self.get_client_role(client_id=client_role_id, role_name=payload["name"])
  1083. if res:
  1084. return res["name"]
  1085. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  1086. data_raw = self.raw_post(
  1087. urls_patterns.URL_ADMIN_CLIENT_ROLES.format(**params_path), data=json.dumps(payload)
  1088. )
  1089. raise_error_from_response(
  1090. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1091. )
  1092. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  1093. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  1094. def add_composite_client_roles_to_role(self, client_role_id, role_name, roles):
  1095. """
  1096. Add composite roles to client role
  1097. :param client_role_id: id of client (not client-id)
  1098. :param role_name: The name of the role
  1099. :param roles: roles list or role (use RoleRepresentation) to be updated
  1100. :return: Keycloak server response
  1101. """
  1102. payload = roles if isinstance(roles, list) else [roles]
  1103. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  1104. data_raw = self.raw_post(
  1105. urls_patterns.URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE.format(**params_path),
  1106. data=json.dumps(payload),
  1107. )
  1108. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1109. def update_client_role(self, client_role_id, role_name, payload):
  1110. """
  1111. Update a client role
  1112. RoleRepresentation
  1113. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1114. :param client_role_id: id of client (not client-id)
  1115. :param role_name: role's name (not id!)
  1116. :param payload: RoleRepresentation
  1117. """
  1118. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  1119. data_raw = self.raw_put(
  1120. urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path), data=json.dumps(payload)
  1121. )
  1122. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1123. def delete_client_role(self, client_role_id, role_name):
  1124. """
  1125. Delete a client role
  1126. RoleRepresentation
  1127. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1128. :param client_role_id: id of client (not client-id)
  1129. :param role_name: role's name (not id!)
  1130. """
  1131. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  1132. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_CLIENT_ROLE.format(**params_path))
  1133. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1134. def assign_client_role(self, user_id, client_id, roles):
  1135. """
  1136. Assign a client role to a user
  1137. :param user_id: id of user
  1138. :param client_id: id of client (not client-id)
  1139. :param roles: roles list or role (use RoleRepresentation)
  1140. :return: Keycloak server response
  1141. """
  1142. payload = roles if isinstance(roles, list) else [roles]
  1143. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1144. data_raw = self.raw_post(
  1145. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1146. data=json.dumps(payload),
  1147. )
  1148. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1149. def get_client_role_members(self, client_id, role_name, **query):
  1150. """
  1151. Get members by client role .
  1152. :param client_id: The client id
  1153. :param role_name: the name of role to be queried.
  1154. :param query: Additional query parameters
  1155. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource)
  1156. :return: Keycloak server response (UserRepresentation)
  1157. """
  1158. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  1159. return self.__fetch_all(
  1160. urls_patterns.URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path), query
  1161. )
  1162. def get_client_role_groups(self, client_id, role_name, **query):
  1163. """
  1164. Get group members by client role .
  1165. :param client_id: The client id
  1166. :param role_name: the name of role to be queried.
  1167. :param query: Additional query parameters
  1168. (see https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource)
  1169. :return: Keycloak server response
  1170. """
  1171. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  1172. return self.__fetch_all(
  1173. urls_patterns.URL_ADMIN_CLIENT_ROLE_GROUPS.format(**params_path), query
  1174. )
  1175. def create_realm_role(self, payload, skip_exists=False):
  1176. """
  1177. Create a new role for the realm or client
  1178. :param payload: The role (use RoleRepresentation)
  1179. :param skip_exists: If true then do not raise an error if realm role already exists
  1180. :return: Realm role name
  1181. """
  1182. if skip_exists:
  1183. role = self.get_realm_role(role_name=payload["name"])
  1184. if role is not None:
  1185. return role["name"]
  1186. params_path = {"realm-name": self.realm_name}
  1187. data_raw = self.raw_post(
  1188. urls_patterns.URL_ADMIN_REALM_ROLES.format(**params_path), data=json.dumps(payload)
  1189. )
  1190. raise_error_from_response(
  1191. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1192. )
  1193. _last_slash_idx = data_raw.headers["Location"].rindex("/")
  1194. return data_raw.headers["Location"][_last_slash_idx + 1 :] # noqa: E203
  1195. def get_realm_role(self, role_name):
  1196. """
  1197. Get realm role by role name
  1198. :param role_name: role's name, not id!
  1199. RoleRepresentation
  1200. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation
  1201. :return: role_id
  1202. """
  1203. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1204. data_raw = self.raw_get(
  1205. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path)
  1206. )
  1207. return raise_error_from_response(data_raw, KeycloakGetError)
  1208. def update_realm_role(self, role_name, payload):
  1209. """
  1210. Update a role for the realm by name
  1211. :param role_name: The name of the role to be updated
  1212. :param payload: The role (use RoleRepresentation)
  1213. :return Keycloak server response
  1214. """
  1215. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1216. data_raw = self.raw_put(
  1217. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  1218. data=json.dumps(payload),
  1219. )
  1220. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1221. def delete_realm_role(self, role_name):
  1222. """
  1223. Delete a role for the realm by name
  1224. :param payload: The role name {'role-name':'name-of-the-role'}
  1225. :return Keycloak server response
  1226. """
  1227. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1228. data_raw = self.raw_delete(
  1229. urls_patterns.URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path)
  1230. )
  1231. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1232. def add_composite_realm_roles_to_role(self, role_name, roles):
  1233. """
  1234. Add composite roles to the role
  1235. :param role_name: The name of the role
  1236. :param roles: roles list or role (use RoleRepresentation) to be updated
  1237. :return: Keycloak server response
  1238. """
  1239. payload = roles if isinstance(roles, list) else [roles]
  1240. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1241. data_raw = self.raw_post(
  1242. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  1243. data=json.dumps(payload),
  1244. )
  1245. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1246. def remove_composite_realm_roles_to_role(self, role_name, roles):
  1247. """
  1248. Remove composite roles from the role
  1249. :param role_name: The name of the role
  1250. :param roles: roles list or role (use RoleRepresentation) to be removed
  1251. :return: Keycloak server response
  1252. """
  1253. payload = roles if isinstance(roles, list) else [roles]
  1254. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1255. data_raw = self.raw_delete(
  1256. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  1257. data=json.dumps(payload),
  1258. )
  1259. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1260. def get_composite_realm_roles_of_role(self, role_name):
  1261. """
  1262. Get composite roles of the role
  1263. :param role_name: The name of the role
  1264. :return: Keycloak server response (array RoleRepresentation)
  1265. """
  1266. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  1267. data_raw = self.raw_get(
  1268. urls_patterns.URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path)
  1269. )
  1270. return raise_error_from_response(data_raw, KeycloakGetError)
  1271. def assign_realm_roles(self, user_id, roles):
  1272. """
  1273. Assign realm roles to a user
  1274. :param user_id: id of user
  1275. :param roles: roles list or role (use RoleRepresentation)
  1276. :return: Keycloak server response
  1277. """
  1278. payload = roles if isinstance(roles, list) else [roles]
  1279. params_path = {"realm-name": self.realm_name, "id": user_id}
  1280. data_raw = self.raw_post(
  1281. urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  1282. data=json.dumps(payload),
  1283. )
  1284. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1285. def delete_realm_roles_of_user(self, user_id, roles):
  1286. """
  1287. Deletes realm roles of a user
  1288. :param user_id: id of user
  1289. :param roles: roles list or role (use RoleRepresentation)
  1290. :return: Keycloak server response
  1291. """
  1292. payload = roles if isinstance(roles, list) else [roles]
  1293. params_path = {"realm-name": self.realm_name, "id": user_id}
  1294. data_raw = self.raw_delete(
  1295. urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  1296. data=json.dumps(payload),
  1297. )
  1298. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1299. def get_realm_roles_of_user(self, user_id):
  1300. """
  1301. Get all realm roles for a user.
  1302. :param user_id: id of user
  1303. :return: Keycloak server response (array RoleRepresentation)
  1304. """
  1305. params_path = {"realm-name": self.realm_name, "id": user_id}
  1306. data_raw = self.raw_get(urls_patterns.URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  1307. return raise_error_from_response(data_raw, KeycloakGetError)
  1308. def get_available_realm_roles_of_user(self, user_id):
  1309. """
  1310. Get all available (i.e. unassigned) realm roles for a user.
  1311. :param user_id: id of user
  1312. :return: Keycloak server response (array RoleRepresentation)
  1313. """
  1314. params_path = {"realm-name": self.realm_name, "id": user_id}
  1315. data_raw = self.raw_get(
  1316. urls_patterns.URL_ADMIN_USER_REALM_ROLES_AVAILABLE.format(**params_path)
  1317. )
  1318. return raise_error_from_response(data_raw, KeycloakGetError)
  1319. def get_composite_realm_roles_of_user(self, user_id):
  1320. """
  1321. Get all composite (i.e. implicit) realm roles for a user.
  1322. :param user_id: id of user
  1323. :return: Keycloak server response (array RoleRepresentation)
  1324. """
  1325. params_path = {"realm-name": self.realm_name, "id": user_id}
  1326. data_raw = self.raw_get(
  1327. urls_patterns.URL_ADMIN_USER_REALM_ROLES_COMPOSITE.format(**params_path)
  1328. )
  1329. return raise_error_from_response(data_raw, KeycloakGetError)
  1330. def assign_group_realm_roles(self, group_id, roles):
  1331. """
  1332. Assign realm roles to a group
  1333. :param group_id: id of groupp
  1334. :param roles: roles list or role (use GroupRoleRepresentation)
  1335. :return: Keycloak server response
  1336. """
  1337. payload = roles if isinstance(roles, list) else [roles]
  1338. params_path = {"realm-name": self.realm_name, "id": group_id}
  1339. data_raw = self.raw_post(
  1340. urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  1341. data=json.dumps(payload),
  1342. )
  1343. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1344. def delete_group_realm_roles(self, group_id, roles):
  1345. """
  1346. Delete realm roles of a group
  1347. :param group_id: id of group
  1348. :param roles: roles list or role (use GroupRoleRepresentation)
  1349. :return: Keycloak server response
  1350. """
  1351. payload = roles if isinstance(roles, list) else [roles]
  1352. params_path = {"realm-name": self.realm_name, "id": group_id}
  1353. data_raw = self.raw_delete(
  1354. urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  1355. data=json.dumps(payload),
  1356. )
  1357. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1358. def get_group_realm_roles(self, group_id):
  1359. """
  1360. Get all realm roles for a group.
  1361. :param user_id: id of the group
  1362. :return: Keycloak server response (array RoleRepresentation)
  1363. """
  1364. params_path = {"realm-name": self.realm_name, "id": group_id}
  1365. data_raw = self.raw_get(urls_patterns.URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path))
  1366. return raise_error_from_response(data_raw, KeycloakGetError)
  1367. def assign_group_client_roles(self, group_id, client_id, roles):
  1368. """
  1369. Assign client roles to a group
  1370. :param group_id: id of group
  1371. :param client_id: id of client (not client-id)
  1372. :param roles: roles list or role (use GroupRoleRepresentation)
  1373. :return: Keycloak server response
  1374. """
  1375. payload = roles if isinstance(roles, list) else [roles]
  1376. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1377. data_raw = self.raw_post(
  1378. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1379. data=json.dumps(payload),
  1380. )
  1381. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  1382. def get_group_client_roles(self, group_id, client_id):
  1383. """
  1384. Get client roles of a group
  1385. :param group_id: id of group
  1386. :param client_id: id of client (not client-id)
  1387. :return: Keycloak server response
  1388. """
  1389. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1390. data_raw = self.raw_get(urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  1391. return raise_error_from_response(data_raw, KeycloakGetError)
  1392. def delete_group_client_roles(self, group_id, client_id, roles):
  1393. """
  1394. Delete client roles of a group
  1395. :param group_id: id of group
  1396. :param client_id: id of client (not client-id)
  1397. :param roles: roles list or role (use GroupRoleRepresentation)
  1398. :return: Keycloak server response (array RoleRepresentation)
  1399. """
  1400. payload = roles if isinstance(roles, list) else [roles]
  1401. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1402. data_raw = self.raw_delete(
  1403. urls_patterns.URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1404. data=json.dumps(payload),
  1405. )
  1406. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1407. def get_client_roles_of_user(self, user_id, client_id):
  1408. """
  1409. Get all client roles for a user.
  1410. :param user_id: id of user
  1411. :param client_id: id of client (not client-id)
  1412. :return: Keycloak server response (array RoleRepresentation)
  1413. """
  1414. return self._get_client_roles_of_user(
  1415. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id
  1416. )
  1417. def get_available_client_roles_of_user(self, user_id, client_id):
  1418. """
  1419. Get available client role-mappings for a user.
  1420. :param user_id: id of user
  1421. :param client_id: id of client (not client-id)
  1422. :return: Keycloak server response (array RoleRepresentation)
  1423. """
  1424. return self._get_client_roles_of_user(
  1425. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id
  1426. )
  1427. def get_composite_client_roles_of_user(self, user_id, client_id):
  1428. """
  1429. Get composite client role-mappings for a user.
  1430. :param user_id: id of user
  1431. :param client_id: id of client (not client-id)
  1432. :return: Keycloak server response (array RoleRepresentation)
  1433. """
  1434. return self._get_client_roles_of_user(
  1435. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id
  1436. )
  1437. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1438. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1439. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1440. return raise_error_from_response(data_raw, KeycloakGetError)
  1441. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1442. """
  1443. Delete client roles from a user.
  1444. :param user_id: id of user
  1445. :param client_id: id of client containing role (not client-id)
  1446. :param roles: roles list or role to delete (use RoleRepresentation)
  1447. :return: Keycloak server response
  1448. """
  1449. payload = roles if isinstance(roles, list) else [roles]
  1450. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1451. data_raw = self.raw_delete(
  1452. urls_patterns.URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1453. data=json.dumps(payload),
  1454. )
  1455. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1456. def get_authentication_flows(self):
  1457. """
  1458. Get authentication flows. Returns all flow details
  1459. AuthenticationFlowRepresentation
  1460. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  1461. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1462. """
  1463. params_path = {"realm-name": self.realm_name}
  1464. data_raw = self.raw_get(urls_patterns.URL_ADMIN_FLOWS.format(**params_path))
  1465. return raise_error_from_response(data_raw, KeycloakGetError)
  1466. def get_authentication_flow_for_id(self, flow_id):
  1467. """
  1468. Get one authentication flow by it's id. Returns all flow details
  1469. AuthenticationFlowRepresentation
  1470. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  1471. :param flow_id: the id of a flow NOT it's alias
  1472. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1473. """
  1474. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1475. data_raw = self.raw_get(urls_patterns.URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1476. return raise_error_from_response(data_raw, KeycloakGetError)
  1477. def create_authentication_flow(self, payload, skip_exists=False):
  1478. """
  1479. Create a new authentication flow
  1480. AuthenticationFlowRepresentation
  1481. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  1482. :param payload: AuthenticationFlowRepresentation
  1483. :param skip_exists: Do not raise an error if authentication flow already exists
  1484. :return: Keycloak server response (RoleRepresentation)
  1485. """
  1486. params_path = {"realm-name": self.realm_name}
  1487. data_raw = self.raw_post(
  1488. urls_patterns.URL_ADMIN_FLOWS.format(**params_path), data=json.dumps(payload)
  1489. )
  1490. return raise_error_from_response(
  1491. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1492. )
  1493. def copy_authentication_flow(self, payload, flow_alias):
  1494. """
  1495. Copy existing authentication flow under a new name. The new name is given as 'newName'
  1496. attribute of the passed payload.
  1497. :param payload: JSON containing 'newName' attribute
  1498. :param flow_alias: the flow alias
  1499. :return: Keycloak server response (RoleRepresentation)
  1500. """
  1501. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1502. data_raw = self.raw_post(
  1503. urls_patterns.URL_ADMIN_FLOWS_COPY.format(**params_path), data=json.dumps(payload)
  1504. )
  1505. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1506. def delete_authentication_flow(self, flow_id):
  1507. """
  1508. Delete authentication flow
  1509. AuthenticationInfoRepresentation
  1510. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationinforepresentation
  1511. :param flow_id: authentication flow id
  1512. :return: Keycloak server response
  1513. """
  1514. params_path = {"realm-name": self.realm_name, "id": flow_id}
  1515. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_FLOW.format(**params_path))
  1516. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1517. def get_authentication_flow_executions(self, flow_alias):
  1518. """
  1519. Get authentication flow executions. Returns all execution steps
  1520. :param flow_alias: the flow alias
  1521. :return: Response(json)
  1522. """
  1523. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1524. data_raw = self.raw_get(urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1525. return raise_error_from_response(data_raw, KeycloakGetError)
  1526. def update_authentication_flow_executions(self, payload, flow_alias):
  1527. """
  1528. Update an authentication flow execution
  1529. AuthenticationExecutionInfoRepresentation
  1530. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1531. :param payload: AuthenticationExecutionInfoRepresentation
  1532. :param flow_alias: The flow alias
  1533. :return: Keycloak server response
  1534. """
  1535. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1536. data_raw = self.raw_put(
  1537. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1538. data=json.dumps(payload),
  1539. )
  1540. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[202, 204])
  1541. def get_authentication_flow_execution(self, execution_id):
  1542. """
  1543. Get authentication flow execution.
  1544. AuthenticationExecutionInfoRepresentation
  1545. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1546. :param execution_id: the execution ID
  1547. :return: Response(json)
  1548. """
  1549. params_path = {"realm-name": self.realm_name, "id": execution_id}
  1550. data_raw = self.raw_get(urls_patterns.URL_ADMIN_FLOWS_EXECUTION.format(**params_path))
  1551. return raise_error_from_response(data_raw, KeycloakGetError)
  1552. def create_authentication_flow_execution(self, payload, flow_alias):
  1553. """
  1554. Create an authentication flow execution
  1555. AuthenticationExecutionInfoRepresentation
  1556. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1557. :param payload: AuthenticationExecutionInfoRepresentation
  1558. :param flow_alias: The flow alias
  1559. :return: Keycloak server response
  1560. """
  1561. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1562. data_raw = self.raw_post(
  1563. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS_EXECUTION.format(**params_path),
  1564. data=json.dumps(payload),
  1565. )
  1566. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1567. def delete_authentication_flow_execution(self, execution_id):
  1568. """
  1569. Delete authentication flow execution
  1570. AuthenticationExecutionInfoRepresentation
  1571. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1572. :param execution_id: keycloak client id (not oauth client-id)
  1573. :return: Keycloak server response (json)
  1574. """
  1575. params_path = {"realm-name": self.realm_name, "id": execution_id}
  1576. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_FLOWS_EXECUTION.format(**params_path))
  1577. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1578. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1579. """
  1580. Create a new sub authentication flow for a given authentication flow
  1581. AuthenticationFlowRepresentation
  1582. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation
  1583. :param payload: AuthenticationFlowRepresentation
  1584. :param flow_alias: The flow alias
  1585. :param skip_exists: Do not raise an error if authentication flow already exists
  1586. :return: Keycloak server response (RoleRepresentation)
  1587. """
  1588. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1589. data_raw = self.raw_post(
  1590. urls_patterns.URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1591. data=json.dumps(payload),
  1592. )
  1593. return raise_error_from_response(
  1594. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1595. )
  1596. def get_authenticator_providers(self):
  1597. """
  1598. Get authenticator providers list.
  1599. :return: Response(json)
  1600. """
  1601. params_path = {"realm-name": self.realm_name}
  1602. data_raw = self.raw_get(
  1603. urls_patterns.URL_ADMIN_AUTHENTICATOR_PROVIDERS.format(**params_path)
  1604. )
  1605. return raise_error_from_response(data_raw, KeycloakGetError)
  1606. def get_authenticator_provider_config_description(self, provider_id):
  1607. """
  1608. Get authenticator's provider configuration description.
  1609. AuthenticatorConfigInfoRepresentation
  1610. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfiginforepresentation
  1611. :param provider_id: Provider Id
  1612. :return: AuthenticatorConfigInfoRepresentation
  1613. """
  1614. params_path = {"realm-name": self.realm_name, "provider-id": provider_id}
  1615. data_raw = self.raw_get(
  1616. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG_DESCRIPTION.format(**params_path)
  1617. )
  1618. return raise_error_from_response(data_raw, KeycloakGetError)
  1619. def get_authenticator_config(self, config_id):
  1620. """
  1621. Get authenticator configuration. Returns all configuration details.
  1622. :param config_id: Authenticator config id
  1623. :return: Response(json)
  1624. """
  1625. params_path = {"realm-name": self.realm_name, "id": config_id}
  1626. data_raw = self.raw_get(urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1627. return raise_error_from_response(data_raw, KeycloakGetError)
  1628. def update_authenticator_config(self, payload, config_id):
  1629. """
  1630. Update an authenticator configuration.
  1631. AuthenticatorConfigRepresentation
  1632. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfigrepresentation
  1633. :param payload: AuthenticatorConfigRepresentation
  1634. :param config_id: Authenticator config id
  1635. :return: Response(json)
  1636. """
  1637. params_path = {"realm-name": self.realm_name, "id": config_id}
  1638. data_raw = self.raw_put(
  1639. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1640. data=json.dumps(payload),
  1641. )
  1642. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1643. def delete_authenticator_config(self, config_id):
  1644. """
  1645. Delete a authenticator configuration.
  1646. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authentication_management_resource
  1647. :param config_id: Authenticator config id
  1648. :return: Keycloak server Response
  1649. """
  1650. params_path = {"realm-name": self.realm_name, "id": config_id}
  1651. data_raw = self.raw_delete(
  1652. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path)
  1653. )
  1654. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1655. def sync_users(self, storage_id, action):
  1656. """
  1657. Function to trigger user sync from provider
  1658. :param storage_id: The id of the user storage provider
  1659. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1660. :return:
  1661. """
  1662. data = {"action": action}
  1663. params_query = {"action": action}
  1664. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1665. data_raw = self.raw_post(
  1666. urls_patterns.URL_ADMIN_USER_STORAGE.format(**params_path),
  1667. data=json.dumps(data),
  1668. **params_query
  1669. )
  1670. return raise_error_from_response(data_raw, KeycloakPostError)
  1671. def get_client_scopes(self):
  1672. """
  1673. Get representation of the client scopes for the realm where we are connected to
  1674. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1675. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1676. """
  1677. params_path = {"realm-name": self.realm_name}
  1678. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1679. return raise_error_from_response(data_raw, KeycloakGetError)
  1680. def get_client_scope(self, client_scope_id):
  1681. """
  1682. Get representation of the client scopes for the realm where we are connected to
  1683. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1684. :param client_scope_id: The id of the client scope
  1685. :return: Keycloak server response (ClientScopeRepresentation)
  1686. """
  1687. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1688. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1689. return raise_error_from_response(data_raw, KeycloakGetError)
  1690. def create_client_scope(self, payload, skip_exists=False):
  1691. """
  1692. Create a client scope
  1693. ClientScopeRepresentation:
  1694. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1695. :param payload: ClientScopeRepresentation
  1696. :param skip_exists: If true then do not raise an error if client scope already exists
  1697. :return: Keycloak server response (ClientScopeRepresentation)
  1698. """
  1699. params_path = {"realm-name": self.realm_name}
  1700. data_raw = self.raw_post(
  1701. urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path), data=json.dumps(payload)
  1702. )
  1703. return raise_error_from_response(
  1704. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1705. )
  1706. def update_client_scope(self, client_scope_id, payload):
  1707. """
  1708. Update a client scope
  1709. ClientScopeRepresentation:
  1710. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource
  1711. :param client_scope_id: The id of the client scope
  1712. :param payload: ClientScopeRepresentation
  1713. :return: Keycloak server response (ClientScopeRepresentation)
  1714. """
  1715. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1716. data_raw = self.raw_put(
  1717. urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path), data=json.dumps(payload)
  1718. )
  1719. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1720. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1721. """
  1722. Add a mapper to a client scope
  1723. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  1724. :param client_scope_id: The id of the client scope
  1725. :param payload: ProtocolMapperRepresentation
  1726. :return: Keycloak server Response
  1727. """
  1728. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1729. data_raw = self.raw_post(
  1730. urls_patterns.URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path),
  1731. data=json.dumps(payload),
  1732. )
  1733. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1734. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1735. """
  1736. Delete a mapper from a client scope
  1737. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_delete_mapper
  1738. :param client_scope_id: The id of the client scope
  1739. :param payload: ProtocolMapperRepresentation
  1740. :return: Keycloak server Response
  1741. """
  1742. params_path = {
  1743. "realm-name": self.realm_name,
  1744. "scope-id": client_scope_id,
  1745. "protocol-mapper-id": protocol_mppaer_id,
  1746. }
  1747. data_raw = self.raw_delete(
  1748. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path)
  1749. )
  1750. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1751. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  1752. """
  1753. Update an existing protocol mapper in a client scope
  1754. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource
  1755. :param client_scope_id: The id of the client scope
  1756. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  1757. and should to be updated
  1758. :param payload: ProtocolMapperRepresentation
  1759. :return: Keycloak server Response
  1760. """
  1761. params_path = {
  1762. "realm-name": self.realm_name,
  1763. "scope-id": client_scope_id,
  1764. "protocol-mapper-id": protocol_mapper_id,
  1765. }
  1766. data_raw = self.raw_put(
  1767. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path),
  1768. data=json.dumps(payload),
  1769. )
  1770. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1771. def get_default_default_client_scopes(self):
  1772. """
  1773. Return list of default default client scopes
  1774. :return: Keycloak server response
  1775. """
  1776. params_path = {"realm-name": self.realm_name}
  1777. data_raw = self.raw_get(
  1778. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPES.format(**params_path)
  1779. )
  1780. return raise_error_from_response(data_raw, KeycloakGetError)
  1781. def delete_default_default_client_scope(self, scope_id):
  1782. """
  1783. Delete default default client scope
  1784. :param scope_id: default default client scope id
  1785. :return: Keycloak server response
  1786. """
  1787. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1788. data_raw = self.raw_delete(
  1789. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path)
  1790. )
  1791. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1792. def add_default_default_client_scope(self, scope_id):
  1793. """
  1794. Add default default client scope
  1795. :param scope_id: default default client scope id
  1796. :return: Keycloak server response
  1797. """
  1798. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1799. payload = {"realm": self.realm_name, "clientScopeId": scope_id}
  1800. data_raw = self.raw_put(
  1801. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path),
  1802. data=json.dumps(payload),
  1803. )
  1804. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1805. def get_default_optional_client_scopes(self):
  1806. """
  1807. Return list of default optional client scopes
  1808. :return: Keycloak server response
  1809. """
  1810. params_path = {"realm-name": self.realm_name}
  1811. data_raw = self.raw_get(
  1812. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPES.format(**params_path)
  1813. )
  1814. return raise_error_from_response(data_raw, KeycloakGetError)
  1815. def delete_default_optional_client_scope(self, scope_id):
  1816. """
  1817. Delete default optional client scope
  1818. :param scope_id: default optional client scope id
  1819. :return: Keycloak server response
  1820. """
  1821. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1822. data_raw = self.raw_delete(
  1823. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path)
  1824. )
  1825. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1826. def add_default_optional_client_scope(self, scope_id):
  1827. """
  1828. Add default optional client scope
  1829. :param scope_id: default optional client scope id
  1830. :return: Keycloak server response
  1831. """
  1832. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1833. payload = {"realm": self.realm_name, "clientScopeId": scope_id}
  1834. data_raw = self.raw_put(
  1835. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path),
  1836. data=json.dumps(payload),
  1837. )
  1838. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1839. def add_mapper_to_client(self, client_id, payload):
  1840. """
  1841. Add a mapper to a client
  1842. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  1843. :param client_id: The id of the client
  1844. :param payload: ProtocolMapperRepresentation
  1845. :return: Keycloak server Response
  1846. """
  1847. params_path = {"realm-name": self.realm_name, "id": client_id}
  1848. data_raw = self.raw_post(
  1849. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPERS.format(**params_path),
  1850. data=json.dumps(payload),
  1851. )
  1852. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1853. def update_client_mapper(self, client_id, mapper_id, payload):
  1854. """
  1855. Update client mapper
  1856. :param client_id: The id of the client
  1857. :param client_mapper_id: The id of the mapper to be deleted
  1858. :param payload: ProtocolMapperRepresentation
  1859. :return: Keycloak server response
  1860. """
  1861. params_path = {
  1862. "realm-name": self.realm_name,
  1863. "id": self.client_id,
  1864. "protocol-mapper-id": mapper_id,
  1865. }
  1866. data_raw = self.raw_put(
  1867. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path),
  1868. data=json.dumps(payload),
  1869. )
  1870. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1871. def remove_client_mapper(self, client_id, client_mapper_id):
  1872. """
  1873. Removes a mapper from the client
  1874. https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_protocol_mappers_resource
  1875. :param client_id: The id of the client
  1876. :param client_mapper_id: The id of the mapper to be deleted
  1877. :return: Keycloak server response
  1878. """
  1879. params_path = {
  1880. "realm-name": self.realm_name,
  1881. "id": client_id,
  1882. "protocol-mapper-id": client_mapper_id,
  1883. }
  1884. data_raw = self.raw_delete(
  1885. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path)
  1886. )
  1887. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1888. def generate_client_secrets(self, client_id):
  1889. """
  1890. Generate a new secret for the client
  1891. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_regeneratesecret
  1892. :param client_id: id of client (not client-id)
  1893. :return: Keycloak server response (ClientRepresentation)
  1894. """
  1895. params_path = {"realm-name": self.realm_name, "id": client_id}
  1896. data_raw = self.raw_post(
  1897. urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None
  1898. )
  1899. return raise_error_from_response(data_raw, KeycloakPostError)
  1900. def get_client_secrets(self, client_id):
  1901. """
  1902. Get representation of the client secrets
  1903. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsecret
  1904. :param client_id: id of client (not client-id)
  1905. :return: Keycloak server response (ClientRepresentation)
  1906. """
  1907. params_path = {"realm-name": self.realm_name, "id": client_id}
  1908. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1909. return raise_error_from_response(data_raw, KeycloakGetError)
  1910. def get_components(self, query=None):
  1911. """
  1912. Return a list of components, filtered according to query parameters
  1913. ComponentRepresentation
  1914. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1915. :param query: Query parameters (optional)
  1916. :return: components list
  1917. """
  1918. params_path = {"realm-name": self.realm_name}
  1919. data_raw = self.raw_get(
  1920. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=None, **query
  1921. )
  1922. return raise_error_from_response(data_raw, KeycloakGetError)
  1923. def create_component(self, payload):
  1924. """
  1925. Create a new component.
  1926. ComponentRepresentation
  1927. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1928. :param payload: ComponentRepresentation
  1929. :return: UserRepresentation
  1930. """
  1931. params_path = {"realm-name": self.realm_name}
  1932. data_raw = self.raw_post(
  1933. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=json.dumps(payload)
  1934. )
  1935. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1936. def get_component(self, component_id):
  1937. """
  1938. Get representation of the component
  1939. :param component_id: Component id
  1940. ComponentRepresentation
  1941. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1942. :return: ComponentRepresentation
  1943. """
  1944. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1945. data_raw = self.raw_get(urls_patterns.URL_ADMIN_COMPONENT.format(**params_path))
  1946. return raise_error_from_response(data_raw, KeycloakGetError)
  1947. def update_component(self, component_id, payload):
  1948. """
  1949. Update the component
  1950. :param component_id: Component id
  1951. :param payload: ComponentRepresentation
  1952. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1953. :return: Http response
  1954. """
  1955. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1956. data_raw = self.raw_put(
  1957. urls_patterns.URL_ADMIN_COMPONENT.format(**params_path), data=json.dumps(payload)
  1958. )
  1959. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1960. def delete_component(self, component_id):
  1961. """
  1962. Delete the component
  1963. :param component_id: Component id
  1964. :return: Http response
  1965. """
  1966. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1967. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_COMPONENT.format(**params_path))
  1968. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1969. def get_keys(self):
  1970. """
  1971. Return a list of keys, filtered according to query parameters
  1972. KeysMetadataRepresentation
  1973. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_key_resource
  1974. :return: keys list
  1975. """
  1976. params_path = {"realm-name": self.realm_name}
  1977. data_raw = self.raw_get(urls_patterns.URL_ADMIN_KEYS.format(**params_path), data=None)
  1978. return raise_error_from_response(data_raw, KeycloakGetError)
  1979. def get_events(self, query=None):
  1980. """
  1981. Return a list of events, filtered according to query parameters
  1982. EventRepresentation array
  1983. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_eventrepresentation
  1984. :return: events list
  1985. """
  1986. params_path = {"realm-name": self.realm_name}
  1987. data_raw = self.raw_get(
  1988. urls_patterns.URL_ADMIN_EVENTS.format(**params_path), data=None, **query
  1989. )
  1990. return raise_error_from_response(data_raw, KeycloakGetError)
  1991. def set_events(self, payload):
  1992. """
  1993. Set realm events configuration
  1994. RealmEventsConfigRepresentation
  1995. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmeventsconfigrepresentation
  1996. :return: Http response
  1997. """
  1998. params_path = {"realm-name": self.realm_name}
  1999. data_raw = self.raw_put(
  2000. urls_patterns.URL_ADMIN_EVENTS.format(**params_path), data=json.dumps(payload)
  2001. )
  2002. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  2003. def raw_get(self, *args, **kwargs):
  2004. """
  2005. Calls connection.raw_get.
  2006. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  2007. and try *get* once more.
  2008. """
  2009. r = self.connection.raw_get(*args, **kwargs)
  2010. if "get" in self.auto_refresh_token and r.status_code == 401:
  2011. self.refresh_token()
  2012. return self.connection.raw_get(*args, **kwargs)
  2013. return r
  2014. def raw_post(self, *args, **kwargs):
  2015. """
  2016. Calls connection.raw_post.
  2017. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  2018. and try *post* once more.
  2019. """
  2020. r = self.connection.raw_post(*args, **kwargs)
  2021. if "post" in self.auto_refresh_token and r.status_code == 401:
  2022. self.refresh_token()
  2023. return self.connection.raw_post(*args, **kwargs)
  2024. return r
  2025. def raw_put(self, *args, **kwargs):
  2026. """
  2027. Calls connection.raw_put.
  2028. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  2029. and try *put* once more.
  2030. """
  2031. r = self.connection.raw_put(*args, **kwargs)
  2032. if "put" in self.auto_refresh_token and r.status_code == 401:
  2033. self.refresh_token()
  2034. return self.connection.raw_put(*args, **kwargs)
  2035. return r
  2036. def raw_delete(self, *args, **kwargs):
  2037. """
  2038. Calls connection.raw_delete.
  2039. If auto_refresh is set for *delete* and *access_token* is expired,
  2040. it will refresh the token and try *delete* once more.
  2041. """
  2042. r = self.connection.raw_delete(*args, **kwargs)
  2043. if "delete" in self.auto_refresh_token and r.status_code == 401:
  2044. self.refresh_token()
  2045. return self.connection.raw_delete(*args, **kwargs)
  2046. return r
  2047. def get_token(self):
  2048. if self.user_realm_name:
  2049. token_realm_name = self.user_realm_name
  2050. elif self.realm_name:
  2051. token_realm_name = self.realm_name
  2052. else:
  2053. token_realm_name = "master"
  2054. self.keycloak_openid = KeycloakOpenID(
  2055. server_url=self.server_url,
  2056. client_id=self.client_id,
  2057. realm_name=token_realm_name,
  2058. verify=self.verify,
  2059. client_secret_key=self.client_secret_key,
  2060. custom_headers=self.custom_headers,
  2061. )
  2062. grant_type = ["password"]
  2063. if self.client_secret_key:
  2064. grant_type = ["client_credentials"]
  2065. if self.user_realm_name:
  2066. self.realm_name = self.user_realm_name
  2067. if self.username and self.password:
  2068. self.token = self.keycloak_openid.token(
  2069. self.username, self.password, grant_type=grant_type, totp=self.totp
  2070. )
  2071. headers = {
  2072. "Authorization": "Bearer " + self.token.get("access_token"),
  2073. "Content-Type": "application/json",
  2074. }
  2075. else:
  2076. self.token = None
  2077. headers = {}
  2078. if self.custom_headers is not None:
  2079. # merge custom headers to main headers
  2080. headers.update(self.custom_headers)
  2081. self.connection = ConnectionManager(
  2082. base_url=self.server_url, headers=headers, timeout=60, verify=self.verify
  2083. )
  2084. def refresh_token(self):
  2085. refresh_token = self.token.get("refresh_token", None)
  2086. if refresh_token is None:
  2087. self.get_token()
  2088. else:
  2089. try:
  2090. self.token = self.keycloak_openid.refresh_token(refresh_token)
  2091. except KeycloakGetError as e:
  2092. list_errors = [
  2093. b"Refresh token expired",
  2094. b"Token is not active",
  2095. b"Session not active",
  2096. ]
  2097. if e.response_code == 400 and any(err in e.response_body for err in list_errors):
  2098. self.get_token()
  2099. else:
  2100. raise
  2101. self.connection.add_param_headers(
  2102. "Authorization", "Bearer " + self.token.get("access_token")
  2103. )
  2104. def get_client_all_sessions(self, client_id):
  2105. """
  2106. Get sessions associated with the client
  2107. :param client_id: id of client
  2108. UserSessionRepresentation
  2109. http://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation
  2110. :return: UserSessionRepresentation
  2111. """
  2112. params_path = {"realm-name": self.realm_name, "id": client_id}
  2113. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  2114. return raise_error_from_response(data_raw, KeycloakGetError)
  2115. def get_client_sessions_stats(self):
  2116. """
  2117. Get current session count for all clients with active sessions
  2118. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsessionstats
  2119. :return: Dict of clients and session count
  2120. """
  2121. params_path = {"realm-name": self.realm_name}
  2122. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SESSION_STATS.format(**params_path))
  2123. return raise_error_from_response(data_raw, KeycloakGetError)