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.

2611 lines
96 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
4 years ago
4 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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_config(self, config_id):
  1597. """
  1598. Get authenticator configuration. Returns all configuration details.
  1599. :param config_id: Authenticator config id
  1600. :return: Response(json)
  1601. """
  1602. params_path = {"realm-name": self.realm_name, "id": config_id}
  1603. data_raw = self.raw_get(urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1604. return raise_error_from_response(data_raw, KeycloakGetError)
  1605. def update_authenticator_config(self, payload, config_id):
  1606. """
  1607. Update an authenticator configuration.
  1608. AuthenticatorConfigRepresentation
  1609. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfigrepresentation
  1610. :param payload: AuthenticatorConfigRepresentation
  1611. :param config_id: Authenticator config id
  1612. :return: Response(json)
  1613. """
  1614. params_path = {"realm-name": self.realm_name, "id": config_id}
  1615. data_raw = self.raw_put(
  1616. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1617. data=json.dumps(payload),
  1618. )
  1619. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1620. def delete_authenticator_config(self, config_id):
  1621. """
  1622. Delete a authenticator configuration.
  1623. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authentication_management_resource
  1624. :param config_id: Authenticator config id
  1625. :return: Keycloak server Response
  1626. """
  1627. params_path = {"realm-name": self.realm_name, "id": config_id}
  1628. data_raw = self.raw_delete(
  1629. urls_patterns.URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path)
  1630. )
  1631. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1632. def sync_users(self, storage_id, action):
  1633. """
  1634. Function to trigger user sync from provider
  1635. :param storage_id: The id of the user storage provider
  1636. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1637. :return:
  1638. """
  1639. data = {"action": action}
  1640. params_query = {"action": action}
  1641. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1642. data_raw = self.raw_post(
  1643. urls_patterns.URL_ADMIN_USER_STORAGE.format(**params_path),
  1644. data=json.dumps(data),
  1645. **params_query
  1646. )
  1647. return raise_error_from_response(data_raw, KeycloakPostError)
  1648. def get_client_scopes(self):
  1649. """
  1650. Get representation of the client scopes for the realm where we are connected to
  1651. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1652. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1653. """
  1654. params_path = {"realm-name": self.realm_name}
  1655. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1656. return raise_error_from_response(data_raw, KeycloakGetError)
  1657. def get_client_scope(self, client_scope_id):
  1658. """
  1659. Get representation of the client scopes for the realm where we are connected to
  1660. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1661. :param client_scope_id: The id of the client scope
  1662. :return: Keycloak server response (ClientScopeRepresentation)
  1663. """
  1664. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1665. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1666. return raise_error_from_response(data_raw, KeycloakGetError)
  1667. def create_client_scope(self, payload, skip_exists=False):
  1668. """
  1669. Create a client scope
  1670. ClientScopeRepresentation:
  1671. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes
  1672. :param payload: ClientScopeRepresentation
  1673. :param skip_exists: If true then do not raise an error if client scope already exists
  1674. :return: Keycloak server response (ClientScopeRepresentation)
  1675. """
  1676. params_path = {"realm-name": self.realm_name}
  1677. data_raw = self.raw_post(
  1678. urls_patterns.URL_ADMIN_CLIENT_SCOPES.format(**params_path), data=json.dumps(payload)
  1679. )
  1680. return raise_error_from_response(
  1681. data_raw, KeycloakPostError, expected_codes=[201], skip_exists=skip_exists
  1682. )
  1683. def update_client_scope(self, client_scope_id, payload):
  1684. """
  1685. Update a client scope
  1686. ClientScopeRepresentation:
  1687. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource
  1688. :param client_scope_id: The id of the client scope
  1689. :param payload: ClientScopeRepresentation
  1690. :return: Keycloak server response (ClientScopeRepresentation)
  1691. """
  1692. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1693. data_raw = self.raw_put(
  1694. urls_patterns.URL_ADMIN_CLIENT_SCOPE.format(**params_path), data=json.dumps(payload)
  1695. )
  1696. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1697. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1698. """
  1699. Add a mapper to a client scope
  1700. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  1701. :param client_scope_id: The id of the client scope
  1702. :param payload: ProtocolMapperRepresentation
  1703. :return: Keycloak server Response
  1704. """
  1705. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1706. data_raw = self.raw_post(
  1707. urls_patterns.URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path),
  1708. data=json.dumps(payload),
  1709. )
  1710. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1711. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1712. """
  1713. Delete a mapper from a client scope
  1714. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_delete_mapper
  1715. :param client_scope_id: The id of the client scope
  1716. :param payload: ProtocolMapperRepresentation
  1717. :return: Keycloak server Response
  1718. """
  1719. params_path = {
  1720. "realm-name": self.realm_name,
  1721. "scope-id": client_scope_id,
  1722. "protocol-mapper-id": protocol_mppaer_id,
  1723. }
  1724. data_raw = self.raw_delete(
  1725. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path)
  1726. )
  1727. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1728. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  1729. """
  1730. Update an existing protocol mapper in a client scope
  1731. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource
  1732. :param client_scope_id: The id of the client scope
  1733. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  1734. and should to be updated
  1735. :param payload: ProtocolMapperRepresentation
  1736. :return: Keycloak server Response
  1737. """
  1738. params_path = {
  1739. "realm-name": self.realm_name,
  1740. "scope-id": client_scope_id,
  1741. "protocol-mapper-id": protocol_mapper_id,
  1742. }
  1743. data_raw = self.raw_put(
  1744. urls_patterns.URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path),
  1745. data=json.dumps(payload),
  1746. )
  1747. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1748. def get_default_default_client_scopes(self):
  1749. """
  1750. Return list of default default client scopes
  1751. :return: Keycloak server response
  1752. """
  1753. params_path = {"realm-name": self.realm_name}
  1754. data_raw = self.raw_get(
  1755. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPES.format(**params_path)
  1756. )
  1757. return raise_error_from_response(data_raw, KeycloakGetError)
  1758. def delete_default_default_client_scope(self, scope_id):
  1759. """
  1760. Delete default default client scope
  1761. :param scope_id: default default client scope id
  1762. :return: Keycloak server response
  1763. """
  1764. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1765. data_raw = self.raw_delete(
  1766. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path)
  1767. )
  1768. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1769. def add_default_default_client_scope(self, scope_id):
  1770. """
  1771. Add default default client scope
  1772. :param scope_id: default default client scope id
  1773. :return: Keycloak server response
  1774. """
  1775. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1776. payload = {"realm": self.realm_name, "clientScopeId": scope_id}
  1777. data_raw = self.raw_put(
  1778. urls_patterns.URL_ADMIN_DEFAULT_DEFAULT_CLIENT_SCOPE.format(**params_path),
  1779. data=json.dumps(payload),
  1780. )
  1781. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1782. def get_default_optional_client_scopes(self):
  1783. """
  1784. Return list of default optional client scopes
  1785. :return: Keycloak server response
  1786. """
  1787. params_path = {"realm-name": self.realm_name}
  1788. data_raw = self.raw_get(
  1789. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPES.format(**params_path)
  1790. )
  1791. return raise_error_from_response(data_raw, KeycloakGetError)
  1792. def delete_default_optional_client_scope(self, scope_id):
  1793. """
  1794. Delete default optional client scope
  1795. :param scope_id: default optional client scope id
  1796. :return: Keycloak server response
  1797. """
  1798. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1799. data_raw = self.raw_delete(
  1800. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path)
  1801. )
  1802. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1803. def add_default_optional_client_scope(self, scope_id):
  1804. """
  1805. Add default optional client scope
  1806. :param scope_id: default optional client scope id
  1807. :return: Keycloak server response
  1808. """
  1809. params_path = {"realm-name": self.realm_name, "id": scope_id}
  1810. payload = {"realm": self.realm_name, "clientScopeId": scope_id}
  1811. data_raw = self.raw_put(
  1812. urls_patterns.URL_ADMIN_DEFAULT_OPTIONAL_CLIENT_SCOPE.format(**params_path),
  1813. data=json.dumps(payload),
  1814. )
  1815. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1816. def add_mapper_to_client(self, client_id, payload):
  1817. """
  1818. Add a mapper to a client
  1819. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper
  1820. :param client_id: The id of the client
  1821. :param payload: ProtocolMapperRepresentation
  1822. :return: Keycloak server Response
  1823. """
  1824. params_path = {"realm-name": self.realm_name, "id": client_id}
  1825. data_raw = self.raw_post(
  1826. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPERS.format(**params_path),
  1827. data=json.dumps(payload),
  1828. )
  1829. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1830. def update_client_mapper(self, client_id, mapper_id, payload):
  1831. """
  1832. Update client mapper
  1833. :param client_id: The id of the client
  1834. :param client_mapper_id: The id of the mapper to be deleted
  1835. :param payload: ProtocolMapperRepresentation
  1836. :return: Keycloak server response
  1837. """
  1838. params_path = {
  1839. "realm-name": self.realm_name,
  1840. "id": self.client_id,
  1841. "protocol-mapper-id": mapper_id,
  1842. }
  1843. data_raw = self.raw_put(
  1844. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path),
  1845. data=json.dumps(payload),
  1846. )
  1847. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1848. def remove_client_mapper(self, client_id, client_mapper_id):
  1849. """
  1850. Removes a mapper from the client
  1851. https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_protocol_mappers_resource
  1852. :param client_id: The id of the client
  1853. :param client_mapper_id: The id of the mapper to be deleted
  1854. :return: Keycloak server response
  1855. """
  1856. params_path = {
  1857. "realm-name": self.realm_name,
  1858. "id": client_id,
  1859. "protocol-mapper-id": client_mapper_id,
  1860. }
  1861. data_raw = self.raw_delete(
  1862. urls_patterns.URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path)
  1863. )
  1864. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1865. def generate_client_secrets(self, client_id):
  1866. """
  1867. Generate a new secret for the client
  1868. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_regeneratesecret
  1869. :param client_id: id of client (not client-id)
  1870. :return: Keycloak server response (ClientRepresentation)
  1871. """
  1872. params_path = {"realm-name": self.realm_name, "id": client_id}
  1873. data_raw = self.raw_post(
  1874. urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None
  1875. )
  1876. return raise_error_from_response(data_raw, KeycloakPostError)
  1877. def get_client_secrets(self, client_id):
  1878. """
  1879. Get representation of the client secrets
  1880. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsecret
  1881. :param client_id: id of client (not client-id)
  1882. :return: Keycloak server response (ClientRepresentation)
  1883. """
  1884. params_path = {"realm-name": self.realm_name, "id": client_id}
  1885. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1886. return raise_error_from_response(data_raw, KeycloakGetError)
  1887. def get_components(self, query=None):
  1888. """
  1889. Return a list of components, filtered according to query parameters
  1890. ComponentRepresentation
  1891. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1892. :param query: Query parameters (optional)
  1893. :return: components list
  1894. """
  1895. params_path = {"realm-name": self.realm_name}
  1896. data_raw = self.raw_get(
  1897. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=None, **query
  1898. )
  1899. return raise_error_from_response(data_raw, KeycloakGetError)
  1900. def create_component(self, payload):
  1901. """
  1902. Create a new component.
  1903. ComponentRepresentation
  1904. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1905. :param payload: ComponentRepresentation
  1906. :return: UserRepresentation
  1907. """
  1908. params_path = {"realm-name": self.realm_name}
  1909. data_raw = self.raw_post(
  1910. urls_patterns.URL_ADMIN_COMPONENTS.format(**params_path), data=json.dumps(payload)
  1911. )
  1912. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[201])
  1913. def get_component(self, component_id):
  1914. """
  1915. Get representation of the component
  1916. :param component_id: Component id
  1917. ComponentRepresentation
  1918. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1919. :return: ComponentRepresentation
  1920. """
  1921. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1922. data_raw = self.raw_get(urls_patterns.URL_ADMIN_COMPONENT.format(**params_path))
  1923. return raise_error_from_response(data_raw, KeycloakGetError)
  1924. def update_component(self, component_id, payload):
  1925. """
  1926. Update the component
  1927. :param component_id: Component id
  1928. :param payload: ComponentRepresentation
  1929. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation
  1930. :return: Http response
  1931. """
  1932. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1933. data_raw = self.raw_put(
  1934. urls_patterns.URL_ADMIN_COMPONENT.format(**params_path), data=json.dumps(payload)
  1935. )
  1936. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1937. def delete_component(self, component_id):
  1938. """
  1939. Delete the component
  1940. :param component_id: Component id
  1941. :return: Http response
  1942. """
  1943. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1944. data_raw = self.raw_delete(urls_patterns.URL_ADMIN_COMPONENT.format(**params_path))
  1945. return raise_error_from_response(data_raw, KeycloakDeleteError, expected_codes=[204])
  1946. def get_keys(self):
  1947. """
  1948. Return a list of keys, filtered according to query parameters
  1949. KeysMetadataRepresentation
  1950. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_key_resource
  1951. :return: keys list
  1952. """
  1953. params_path = {"realm-name": self.realm_name}
  1954. data_raw = self.raw_get(urls_patterns.URL_ADMIN_KEYS.format(**params_path), data=None)
  1955. return raise_error_from_response(data_raw, KeycloakGetError)
  1956. def get_events(self, query=None):
  1957. """
  1958. Return a list of events, filtered according to query parameters
  1959. EventRepresentation array
  1960. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_eventrepresentation
  1961. :return: events list
  1962. """
  1963. params_path = {"realm-name": self.realm_name}
  1964. data_raw = self.raw_get(
  1965. urls_patterns.URL_ADMIN_EVENTS.format(**params_path), data=None, **query
  1966. )
  1967. return raise_error_from_response(data_raw, KeycloakGetError)
  1968. def set_events(self, payload):
  1969. """
  1970. Set realm events configuration
  1971. RealmEventsConfigRepresentation
  1972. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmeventsconfigrepresentation
  1973. :return: Http response
  1974. """
  1975. params_path = {"realm-name": self.realm_name}
  1976. data_raw = self.raw_put(
  1977. urls_patterns.URL_ADMIN_EVENTS.format(**params_path), data=json.dumps(payload)
  1978. )
  1979. return raise_error_from_response(data_raw, KeycloakPutError, expected_codes=[204])
  1980. def raw_get(self, *args, **kwargs):
  1981. """
  1982. Calls connection.raw_get.
  1983. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1984. and try *get* once more.
  1985. """
  1986. r = self.connection.raw_get(*args, **kwargs)
  1987. if "get" in self.auto_refresh_token and r.status_code == 401:
  1988. self.refresh_token()
  1989. return self.connection.raw_get(*args, **kwargs)
  1990. return r
  1991. def raw_post(self, *args, **kwargs):
  1992. """
  1993. Calls connection.raw_post.
  1994. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1995. and try *post* once more.
  1996. """
  1997. r = self.connection.raw_post(*args, **kwargs)
  1998. if "post" in self.auto_refresh_token and r.status_code == 401:
  1999. self.refresh_token()
  2000. return self.connection.raw_post(*args, **kwargs)
  2001. return r
  2002. def raw_put(self, *args, **kwargs):
  2003. """
  2004. Calls connection.raw_put.
  2005. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  2006. and try *put* once more.
  2007. """
  2008. r = self.connection.raw_put(*args, **kwargs)
  2009. if "put" in self.auto_refresh_token and r.status_code == 401:
  2010. self.refresh_token()
  2011. return self.connection.raw_put(*args, **kwargs)
  2012. return r
  2013. def raw_delete(self, *args, **kwargs):
  2014. """
  2015. Calls connection.raw_delete.
  2016. If auto_refresh is set for *delete* and *access_token* is expired,
  2017. it will refresh the token and try *delete* once more.
  2018. """
  2019. r = self.connection.raw_delete(*args, **kwargs)
  2020. if "delete" in self.auto_refresh_token and r.status_code == 401:
  2021. self.refresh_token()
  2022. return self.connection.raw_delete(*args, **kwargs)
  2023. return r
  2024. def get_token(self):
  2025. if self.user_realm_name:
  2026. token_realm_name = self.user_realm_name
  2027. elif self.realm_name:
  2028. token_realm_name = self.realm_name
  2029. else:
  2030. token_realm_name = "master"
  2031. self.keycloak_openid = KeycloakOpenID(
  2032. server_url=self.server_url,
  2033. client_id=self.client_id,
  2034. realm_name=token_realm_name,
  2035. verify=self.verify,
  2036. client_secret_key=self.client_secret_key,
  2037. custom_headers=self.custom_headers,
  2038. )
  2039. grant_type = ["password"]
  2040. if self.client_secret_key:
  2041. grant_type = ["client_credentials"]
  2042. if self.user_realm_name:
  2043. self.realm_name = self.user_realm_name
  2044. if self.username and self.password:
  2045. self.token = self.keycloak_openid.token(
  2046. self.username, self.password, grant_type=grant_type, totp=self.totp
  2047. )
  2048. headers = {
  2049. "Authorization": "Bearer " + self.token.get("access_token"),
  2050. "Content-Type": "application/json",
  2051. }
  2052. else:
  2053. self.token = None
  2054. headers = {}
  2055. if self.custom_headers is not None:
  2056. # merge custom headers to main headers
  2057. headers.update(self.custom_headers)
  2058. self.connection = ConnectionManager(
  2059. base_url=self.server_url, headers=headers, timeout=60, verify=self.verify
  2060. )
  2061. def refresh_token(self):
  2062. refresh_token = self.token.get("refresh_token", None)
  2063. if refresh_token is None:
  2064. self.get_token()
  2065. else:
  2066. try:
  2067. self.token = self.keycloak_openid.refresh_token(refresh_token)
  2068. except KeycloakGetError as e:
  2069. list_errors = [
  2070. b"Refresh token expired",
  2071. b"Token is not active",
  2072. b"Session not active",
  2073. ]
  2074. if e.response_code == 400 and any(err in e.response_body for err in list_errors):
  2075. self.get_token()
  2076. else:
  2077. raise
  2078. self.connection.add_param_headers(
  2079. "Authorization", "Bearer " + self.token.get("access_token")
  2080. )
  2081. def get_client_all_sessions(self, client_id):
  2082. """
  2083. Get sessions associated with the client
  2084. :param client_id: id of client
  2085. UserSessionRepresentation
  2086. http://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation
  2087. :return: UserSessionRepresentation
  2088. """
  2089. params_path = {"realm-name": self.realm_name, "id": client_id}
  2090. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  2091. return raise_error_from_response(data_raw, KeycloakGetError)
  2092. def get_client_sessions_stats(self):
  2093. """
  2094. Get current session count for all clients with active sessions
  2095. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsessionstats
  2096. :return: Dict of clients and session count
  2097. """
  2098. params_path = {"realm-name": self.realm_name}
  2099. data_raw = self.raw_get(urls_patterns.URL_ADMIN_CLIENT_SESSION_STATS.format(**params_path))
  2100. return raise_error_from_response(data_raw, KeycloakGetError)