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.

2643 lines
97 KiB

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