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.

2531 lines
94 KiB

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