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.

1828 lines
72 KiB

7 years ago
6 years ago
6 years ago
4 years ago
6 years ago
7 years ago
6 years ago
4 years ago
4 years ago
4 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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 raise_error_from_response, KeycloakGetError
  30. from .keycloak_openid import KeycloakOpenID
  31. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  32. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_GROUPS_REALM_ROLES, \
  33. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE, URL_ADMIN_CLIENT_INSTALLATION_PROVIDER, \
  34. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GET_GROUPS_REALM_ROLES, URL_ADMIN_GROUPS_CLIENT_ROLES, \
  35. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  36. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  37. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  38. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  39. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, URL_ADMIN_IDP, \
  40. URL_ADMIN_IDP_MAPPERS, URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  41. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  42. URL_ADMIN_USER_REALM_ROLES, URL_ADMIN_REALM, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS, \
  43. URL_ADMIN_USER_FEDERATED_IDENTITY, URL_ADMIN_USER_FEDERATED_IDENTITIES, URL_ADMIN_CLIENT_ROLE_MEMBERS, \
  44. URL_ADMIN_REALM_ROLES_MEMBERS, URL_ADMIN_CLIENT_PROTOCOL_MAPPER, URL_ADMIN_CLIENT_SCOPES_MAPPERS, \
  45. URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION, URL_ADMIN_FLOWS_EXECUTIONS_FLOW, URL_ADMIN_FLOWS_COPY, \
  46. URL_ADMIN_FLOWS_ALIAS, URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER, URL_ADMIN_AUTHENTICATOR_CONFIG, \
  47. URL_ADMIN_CLIENT_ALL_SESSIONS
  48. class KeycloakAdmin:
  49. PAGE_SIZE = 100
  50. _server_url = None
  51. _username = None
  52. _password = None
  53. _realm_name = None
  54. _client_id = None
  55. _verify = None
  56. _client_secret_key = None
  57. _auto_refresh_token = None
  58. _connection = None
  59. _token = None
  60. _custom_headers = None
  61. _user_realm_name = None
  62. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  63. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  64. """
  65. :param server_url: Keycloak server url
  66. :param username: admin username
  67. :param password: admin password
  68. :param realm_name: realm name
  69. :param client_id: client id
  70. :param verify: True if want check connection SSL
  71. :param client_secret_key: client secret key
  72. :param custom_headers: dict of custom header to pass to each HTML request
  73. :param user_realm_name: The realm name of the user, if different from realm_name
  74. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  75. """
  76. self.server_url = server_url
  77. self.username = username
  78. self.password = password
  79. self.realm_name = realm_name
  80. self.client_id = client_id
  81. self.verify = verify
  82. self.client_secret_key = client_secret_key
  83. self.auto_refresh_token = auto_refresh_token or []
  84. self.user_realm_name = user_realm_name
  85. self.custom_headers = custom_headers
  86. # Get token Admin
  87. self.get_token()
  88. @property
  89. def server_url(self):
  90. return self._server_url
  91. @server_url.setter
  92. def server_url(self, value):
  93. self._server_url = value
  94. @property
  95. def realm_name(self):
  96. return self._realm_name
  97. @realm_name.setter
  98. def realm_name(self, value):
  99. self._realm_name = value
  100. @property
  101. def connection(self):
  102. return self._connection
  103. @connection.setter
  104. def connection(self, value):
  105. self._connection = value
  106. @property
  107. def client_id(self):
  108. return self._client_id
  109. @client_id.setter
  110. def client_id(self, value):
  111. self._client_id = value
  112. @property
  113. def client_secret_key(self):
  114. return self._client_secret_key
  115. @client_secret_key.setter
  116. def client_secret_key(self, value):
  117. self._client_secret_key = value
  118. @property
  119. def verify(self):
  120. return self._verify
  121. @verify.setter
  122. def verify(self, value):
  123. self._verify = value
  124. @property
  125. def username(self):
  126. return self._username
  127. @username.setter
  128. def username(self, value):
  129. self._username = value
  130. @property
  131. def password(self):
  132. return self._password
  133. @password.setter
  134. def password(self, value):
  135. self._password = value
  136. @property
  137. def token(self):
  138. return self._token
  139. @token.setter
  140. def token(self, value):
  141. self._token = value
  142. @property
  143. def auto_refresh_token(self):
  144. return self._auto_refresh_token
  145. @property
  146. def user_realm_name(self):
  147. return self._user_realm_name
  148. @user_realm_name.setter
  149. def user_realm_name(self, value):
  150. self._user_realm_name = value
  151. @property
  152. def custom_headers(self):
  153. return self._custom_headers
  154. @custom_headers.setter
  155. def custom_headers(self, value):
  156. self._custom_headers = value
  157. @auto_refresh_token.setter
  158. def auto_refresh_token(self, value):
  159. allowed_methods = {'get', 'post', 'put', 'delete'}
  160. if not isinstance(value, Iterable):
  161. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  162. if not all(method in allowed_methods for method in value):
  163. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  164. self._auto_refresh_token = value
  165. def __fetch_all(self, url, query=None):
  166. '''Wrapper function to paginate GET requests
  167. :param url: The url on which the query is executed
  168. :param query: Existing query parameters (optional)
  169. :return: Combined results of paginated queries
  170. '''
  171. results = []
  172. # initalize query if it was called with None
  173. if not query:
  174. query = {}
  175. page = 0
  176. query['max'] = self.PAGE_SIZE
  177. # fetch until we can
  178. while True:
  179. query['first'] = page*self.PAGE_SIZE
  180. partial_results = raise_error_from_response(
  181. self.raw_get(url, **query),
  182. KeycloakGetError)
  183. if not partial_results:
  184. break
  185. results.extend(partial_results)
  186. page += 1
  187. return results
  188. def import_realm(self, payload):
  189. """
  190. Import a new realm from a RealmRepresentation. Realm name must be unique.
  191. RealmRepresentation
  192. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  193. :param payload: RealmRepresentation
  194. :return: RealmRepresentation
  195. """
  196. data_raw = self.raw_post(URL_ADMIN_REALMS,
  197. data=json.dumps(payload))
  198. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  199. def get_realms(self):
  200. """
  201. Lists all realms in Keycloak deployment
  202. :return: realms list
  203. """
  204. data_raw = self.raw_get(URL_ADMIN_REALMS)
  205. return raise_error_from_response(data_raw, KeycloakGetError)
  206. def create_realm(self, payload, skip_exists=False):
  207. """
  208. Create a realm
  209. RealmRepresentation:
  210. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  211. :param payload: RealmRepresentation
  212. :param skip_exists: Skip if Realm already exist.
  213. :return: Keycloak server response (RealmRepresentation)
  214. """
  215. data_raw = self.raw_post(URL_ADMIN_REALMS,
  216. data=json.dumps(payload))
  217. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  218. def update_realm(self, realm_name, payload):
  219. """
  220. Update a realm. This wil only update top level attributes and will ignore any user,
  221. role, or client information in the payload.
  222. RealmRepresentation:
  223. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  224. :param realm_name: Realm name (not the realm id)
  225. :param payload: RealmRepresentation
  226. :return: Http response
  227. """
  228. params_path = {"realm-name": realm_name}
  229. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  230. data=json.dumps(payload))
  231. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  232. def delete_realm(self, realm_name):
  233. """
  234. Delete a realm
  235. :param realm_name: Realm name (not the realm id)
  236. :return: Http response
  237. """
  238. params_path = {"realm-name": realm_name}
  239. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  240. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  241. def get_users(self, query=None):
  242. """
  243. Return a list of users, filtered according to query parameters
  244. UserRepresentation
  245. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  246. :param query: Query parameters (optional)
  247. :return: users list
  248. """
  249. params_path = {"realm-name": self.realm_name}
  250. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  251. def create_idp(self, payload):
  252. """
  253. Create an ID Provider,
  254. IdentityProviderRepresentation
  255. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  256. :param: payload: IdentityProviderRepresentation
  257. """
  258. params_path = {"realm-name": self.realm_name}
  259. data_raw = self.raw_post(URL_ADMIN_IDPS.format(**params_path),
  260. data=json.dumps(payload))
  261. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  262. def add_mapper_to_idp(self, idp_alias, payload):
  263. """
  264. Create an ID Provider,
  265. IdentityProviderRepresentation
  266. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityprovidermapperrepresentation
  267. :param: idp_alias: alias for Idp to add mapper in
  268. :param: payload: IdentityProviderMapperRepresentation
  269. """
  270. params_path = {"realm-name": self.realm_name, "idp-alias": idp_alias}
  271. data_raw = self.raw_post(URL_ADMIN_IDP_MAPPERS.format(**params_path),
  272. data=json.dumps(payload))
  273. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  274. def get_idps(self):
  275. """
  276. Returns a list of ID Providers,
  277. IdentityProviderRepresentation
  278. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  279. :return: array IdentityProviderRepresentation
  280. """
  281. params_path = {"realm-name": self.realm_name}
  282. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  283. return raise_error_from_response(data_raw, KeycloakGetError)
  284. def delete_idp(self, idp_alias):
  285. """
  286. Deletes ID Provider,
  287. :param: idp_alias: idp alias name
  288. """
  289. params_path = {"realm-name": self.realm_name, "alias": idp_alias}
  290. data_raw = self.raw_delete(URL_ADMIN_IDP.format(**params_path))
  291. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  292. def create_user(self, payload):
  293. """
  294. Create a new user. Username must be unique
  295. UserRepresentation
  296. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  297. :param payload: UserRepresentation
  298. :return: UserRepresentation
  299. """
  300. params_path = {"realm-name": self.realm_name}
  301. exists = self.get_user_id(username=payload['username'])
  302. if exists is not None:
  303. return str(exists)
  304. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  305. data=json.dumps(payload))
  306. raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  307. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  308. return data_raw.headers['Location'][_last_slash_idx + 1:]
  309. def users_count(self):
  310. """
  311. User counter
  312. :return: counter
  313. """
  314. params_path = {"realm-name": self.realm_name}
  315. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  316. return raise_error_from_response(data_raw, KeycloakGetError)
  317. def get_user_id(self, username):
  318. """
  319. Get internal keycloak user id from username
  320. This is required for further actions against this user.
  321. UserRepresentation
  322. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  323. :param username: id in UserRepresentation
  324. :return: user_id
  325. """
  326. users = self.get_users(query={"search": username})
  327. return next((user["id"] for user in users if user["username"] == username), None)
  328. def get_user(self, user_id):
  329. """
  330. Get representation of the user
  331. :param user_id: User id
  332. UserRepresentation
  333. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  334. :return: UserRepresentation
  335. """
  336. params_path = {"realm-name": self.realm_name, "id": user_id}
  337. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  338. return raise_error_from_response(data_raw, KeycloakGetError)
  339. def get_user_groups(self, user_id):
  340. """
  341. Returns a list of groups of which the user is a member
  342. :param user_id: User id
  343. :return: user groups list
  344. """
  345. params_path = {"realm-name": self.realm_name, "id": user_id}
  346. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  347. return raise_error_from_response(data_raw, KeycloakGetError)
  348. def update_user(self, user_id, payload):
  349. """
  350. Update the user
  351. :param user_id: User id
  352. :param payload: UserRepresentation
  353. :return: Http response
  354. """
  355. params_path = {"realm-name": self.realm_name, "id": user_id}
  356. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  357. data=json.dumps(payload))
  358. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  359. def delete_user(self, user_id):
  360. """
  361. Delete the user
  362. :param user_id: User id
  363. :return: Http response
  364. """
  365. params_path = {"realm-name": self.realm_name, "id": user_id}
  366. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  367. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  368. def set_user_password(self, user_id, password, temporary=True):
  369. """
  370. Set up a password for the user. If temporary is True, the user will have to reset
  371. the temporary password next time they log in.
  372. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  373. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  374. :param user_id: User id
  375. :param password: New password
  376. :param temporary: True if password is temporary
  377. :return:
  378. """
  379. payload = {"type": "password", "temporary": temporary, "value": password}
  380. params_path = {"realm-name": self.realm_name, "id": user_id}
  381. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  382. data=json.dumps(payload))
  383. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  384. def consents_user(self, user_id):
  385. """
  386. Get consents granted by the user
  387. :param user_id: User id
  388. :return: consents
  389. """
  390. params_path = {"realm-name": self.realm_name, "id": user_id}
  391. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  392. return raise_error_from_response(data_raw, KeycloakGetError)
  393. def get_user_social_logins(self, user_id):
  394. """
  395. Returns a list of federated identities/social logins of which the user has been associated with
  396. :param user_id: User id
  397. :return: federated identities list
  398. """
  399. params_path = {"realm-name": self.realm_name, "id": user_id}
  400. data_raw = self.raw_get(URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path))
  401. return raise_error_from_response(data_raw, KeycloakGetError)
  402. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  403. """
  404. Add a federated identity / social login provider to the user
  405. :param user_id: User id
  406. :param provider_id: Social login provider id
  407. :param provider_userid: userid specified by the provider
  408. :param provider_username: username specified by the provider
  409. :return:
  410. """
  411. payload = {"identityProvider": provider_id, "userId": provider_userid, "userName": provider_username}
  412. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  413. data_raw = self.raw_post(URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path), data=json.dumps(payload))
  414. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  415. """
  416. Send an update account email to the user. An email contains a
  417. link the user can click to perform a set of required actions.
  418. :param user_id: User id
  419. :param payload: A list of actions for the user to complete
  420. :param client_id: Client id (optional)
  421. :param lifespan: Number of seconds after which the generated token expires (optional)
  422. :param redirect_uri: The redirect uri (optional)
  423. :return:
  424. """
  425. params_path = {"realm-name": self.realm_name, "id": user_id}
  426. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  427. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  428. data=json.dumps(payload), **params_query)
  429. return raise_error_from_response(data_raw, KeycloakGetError)
  430. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  431. """
  432. Send a update account email to the user An email contains a
  433. link the user can click to perform a set of required actions.
  434. :param user_id: User id
  435. :param client_id: Client id (optional)
  436. :param redirect_uri: Redirect uri (optional)
  437. :return:
  438. """
  439. params_path = {"realm-name": self.realm_name, "id": user_id}
  440. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  441. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  442. data={}, **params_query)
  443. return raise_error_from_response(data_raw, KeycloakGetError)
  444. def get_sessions(self, user_id):
  445. """
  446. Get sessions associated with the user
  447. :param user_id: id of user
  448. UserSessionRepresentation
  449. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  450. :return: UserSessionRepresentation
  451. """
  452. params_path = {"realm-name": self.realm_name, "id": user_id}
  453. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  454. return raise_error_from_response(data_raw, KeycloakGetError)
  455. def get_server_info(self):
  456. """
  457. Get themes, social providers, auth providers, and event listeners available on this server
  458. ServerInfoRepresentation
  459. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  460. :return: ServerInfoRepresentation
  461. """
  462. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  463. return raise_error_from_response(data_raw, KeycloakGetError)
  464. def get_groups(self):
  465. """
  466. Returns a list of groups belonging to the realm
  467. GroupRepresentation
  468. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  469. :return: array GroupRepresentation
  470. """
  471. params_path = {"realm-name": self.realm_name}
  472. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  473. def get_group(self, group_id):
  474. """
  475. Get group by id. Returns full group details
  476. GroupRepresentation
  477. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  478. :param group_id: The group id
  479. :return: Keycloak server response (GroupRepresentation)
  480. """
  481. params_path = {"realm-name": self.realm_name, "id": group_id}
  482. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  483. return raise_error_from_response(data_raw, KeycloakGetError)
  484. def get_subgroups(self, group, path):
  485. """
  486. Utility function to iterate through nested group structures
  487. GroupRepresentation
  488. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  489. :param name: group (GroupRepresentation)
  490. :param path: group path (string)
  491. :return: Keycloak server response (GroupRepresentation)
  492. """
  493. for subgroup in group["subGroups"]:
  494. if subgroup['path'] == path:
  495. return subgroup
  496. elif subgroup["subGroups"]:
  497. for subgroup in group["subGroups"]:
  498. result = self.get_subgroups(subgroup, path)
  499. if result:
  500. return result
  501. # went through the tree without hits
  502. return None
  503. def get_group_members(self, group_id, **query):
  504. """
  505. Get members by group id. Returns group members
  506. GroupRepresentation
  507. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  508. :param group_id: The group id
  509. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  510. :return: Keycloak server response (UserRepresentation)
  511. """
  512. params_path = {"realm-name": self.realm_name, "id": group_id}
  513. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  514. def get_group_by_path(self, path, search_in_subgroups=False):
  515. """
  516. Get group id based on name or path.
  517. A straight name or path match with a top-level group will return first.
  518. Subgroups are traversed, the first to match path (or name with path) is returned.
  519. GroupRepresentation
  520. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  521. :param path: group path
  522. :param search_in_subgroups: True if want search in the subgroups
  523. :return: Keycloak server response (GroupRepresentation)
  524. """
  525. groups = self.get_groups()
  526. # TODO: Review this code is necessary
  527. for group in groups:
  528. if group['path'] == path:
  529. return group
  530. elif search_in_subgroups and group["subGroups"]:
  531. for group in group["subGroups"]:
  532. if group['path'] == path:
  533. return group
  534. res = self.get_subgroups(group, path)
  535. if res != None:
  536. return res
  537. return None
  538. def create_group(self, payload, parent=None, skip_exists=False):
  539. """
  540. Creates a group in the Realm
  541. :param payload: GroupRepresentation
  542. :param parent: parent group's id. Required to create a sub-group.
  543. :param skip_exists: If true then do not raise an error if it already exists
  544. GroupRepresentation
  545. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  546. :return: Http response
  547. """
  548. if parent is None:
  549. params_path = {"realm-name": self.realm_name}
  550. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  551. data=json.dumps(payload))
  552. else:
  553. params_path = {"realm-name": self.realm_name, "id": parent, }
  554. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  555. data=json.dumps(payload))
  556. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  557. def update_group(self, group_id, payload):
  558. """
  559. Update group, ignores subgroups.
  560. :param group_id: id of group
  561. :param payload: GroupRepresentation with updated information.
  562. GroupRepresentation
  563. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  564. :return: Http response
  565. """
  566. params_path = {"realm-name": self.realm_name, "id": group_id}
  567. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  568. data=json.dumps(payload))
  569. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  570. def group_set_permissions(self, group_id, enabled=True):
  571. """
  572. Enable/Disable permissions for a group. Cannot delete group if disabled
  573. :param group_id: id of group
  574. :param enabled: boolean
  575. :return: Keycloak server response
  576. """
  577. params_path = {"realm-name": self.realm_name, "id": group_id}
  578. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  579. data=json.dumps({"enabled": enabled}))
  580. return raise_error_from_response(data_raw, KeycloakGetError)
  581. def group_user_add(self, user_id, group_id):
  582. """
  583. Add user to group (user_id and group_id)
  584. :param user_id: id of user
  585. :param group_id: id of group to add to
  586. :return: Keycloak server response
  587. """
  588. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  589. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  590. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  591. def group_user_remove(self, user_id, group_id):
  592. """
  593. Remove user from group (user_id and group_id)
  594. :param user_id: id of user
  595. :param group_id: id of group to remove from
  596. :return: Keycloak server response
  597. """
  598. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  599. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  600. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  601. def delete_group(self, group_id):
  602. """
  603. Deletes a group in the Realm
  604. :param group_id: id of group to delete
  605. :return: Keycloak server response
  606. """
  607. params_path = {"realm-name": self.realm_name, "id": group_id}
  608. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  609. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  610. def get_clients(self):
  611. """
  612. Returns a list of clients belonging to the realm
  613. ClientRepresentation
  614. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  615. :return: Keycloak server response (ClientRepresentation)
  616. """
  617. params_path = {"realm-name": self.realm_name}
  618. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  619. return raise_error_from_response(data_raw, KeycloakGetError)
  620. def get_client(self, client_id):
  621. """
  622. Get representation of the client
  623. ClientRepresentation
  624. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  625. :param client_id: id of client (not client-id)
  626. :return: Keycloak server response (ClientRepresentation)
  627. """
  628. params_path = {"realm-name": self.realm_name, "id": client_id}
  629. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  630. return raise_error_from_response(data_raw, KeycloakGetError)
  631. def get_client_id(self, client_name):
  632. """
  633. Get internal keycloak client id from client-id.
  634. This is required for further actions against this client.
  635. :param client_name: name in ClientRepresentation
  636. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  637. :return: client_id (uuid as string)
  638. """
  639. clients = self.get_clients()
  640. for client in clients:
  641. if client_name == client.get('name') or client_name == client.get('clientId'):
  642. return client["id"]
  643. return None
  644. def get_client_authz_settings(self, client_id):
  645. """
  646. Get authorization json from client.
  647. :param client_id: id in ClientRepresentation
  648. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  649. :return: Keycloak server response
  650. """
  651. params_path = {"realm-name": self.realm_name, "id": client_id}
  652. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  653. return data_raw
  654. def get_client_authz_resources(self, client_id):
  655. """
  656. Get resources from client.
  657. :param client_id: id in ClientRepresentation
  658. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  659. :return: Keycloak server response
  660. """
  661. params_path = {"realm-name": self.realm_name, "id": client_id}
  662. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  663. return data_raw
  664. def get_client_service_account_user(self, client_id):
  665. """
  666. Get service account user from client.
  667. :param client_id: id in ClientRepresentation
  668. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  669. :return: UserRepresentation
  670. """
  671. params_path = {"realm-name": self.realm_name, "id": client_id}
  672. data_raw = self.raw_get(URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path))
  673. return raise_error_from_response(data_raw, KeycloakGetError)
  674. def create_client(self, payload, skip_exists=False):
  675. """
  676. Create a client
  677. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  678. :param skip_exists: If true then do not raise an error if client already exists
  679. :param payload: ClientRepresentation
  680. :return: Keycloak server response (UserRepresentation)
  681. """
  682. params_path = {"realm-name": self.realm_name}
  683. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  684. data=json.dumps(payload))
  685. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  686. def update_client(self, client_id, payload):
  687. """
  688. Update a client
  689. :param client_id: Client id
  690. :param payload: ClientRepresentation
  691. :return: Http response
  692. """
  693. params_path = {"realm-name": self.realm_name, "id": client_id}
  694. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  695. data=json.dumps(payload))
  696. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  697. def delete_client(self, client_id):
  698. """
  699. Get representation of the client
  700. ClientRepresentation
  701. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  702. :param client_id: keycloak client id (not oauth client-id)
  703. :return: Keycloak server response (ClientRepresentation)
  704. """
  705. params_path = {"realm-name": self.realm_name, "id": client_id}
  706. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  707. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  708. def get_client_installation_provider(self, client_id, provider_id):
  709. """
  710. Get content for given installation provider
  711. Related documentation:
  712. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_clients_resource
  713. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  714. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_serverinforepresentation
  715. :param client_id: Client id
  716. :param provider_id: provider id to specify response format
  717. """
  718. params_path = {"realm-name": self.realm_name, "id": client_id, "provider-id": provider_id}
  719. data_raw = self.raw_get(URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path))
  720. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  721. def get_realm_roles(self):
  722. """
  723. Get all roles for the realm or client
  724. RoleRepresentation
  725. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  726. :return: Keycloak server response (RoleRepresentation)
  727. """
  728. params_path = {"realm-name": self.realm_name}
  729. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  730. return raise_error_from_response(data_raw, KeycloakGetError)
  731. def get_realm_role_members(self, role_name, **query):
  732. """
  733. Get role members of realm by role name.
  734. :param role_name: Name of the role.
  735. :param query: Additional Query parameters (see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_roles_resource)
  736. :return: Keycloak Server Response (UserRepresentation)
  737. """
  738. params_path = {"realm-name": self.realm_name, "role-name":role_name}
  739. return self.__fetch_all(URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query)
  740. def get_client_roles(self, client_id):
  741. """
  742. Get all roles for the client
  743. :param client_id: id of client (not client-id)
  744. RoleRepresentation
  745. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  746. :return: Keycloak server response (RoleRepresentation)
  747. """
  748. params_path = {"realm-name": self.realm_name, "id": client_id}
  749. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  750. return raise_error_from_response(data_raw, KeycloakGetError)
  751. def get_client_role(self, client_id, role_name):
  752. """
  753. Get client role id by name
  754. This is required for further actions with this role.
  755. :param client_id: id of client (not client-id)
  756. :param role_name: roles name (not id!)
  757. RoleRepresentation
  758. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  759. :return: role_id
  760. """
  761. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  762. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  763. return raise_error_from_response(data_raw, KeycloakGetError)
  764. def get_client_role_id(self, client_id, role_name):
  765. """
  766. Warning: Deprecated
  767. Get client role id by name
  768. This is required for further actions with this role.
  769. :param client_id: id of client (not client-id)
  770. :param role_name: roles name (not id!)
  771. RoleRepresentation
  772. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  773. :return: role_id
  774. """
  775. role = self.get_client_role(client_id, role_name)
  776. return role.get("id")
  777. def create_client_role(self, client_role_id, payload, skip_exists=False):
  778. """
  779. Create a client role
  780. RoleRepresentation
  781. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  782. :param client_role_id: id of client (not client-id)
  783. :param payload: RoleRepresentation
  784. :param skip_exists: If true then do not raise an error if client role already exists
  785. :return: Keycloak server response (RoleRepresentation)
  786. """
  787. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  788. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  789. data=json.dumps(payload))
  790. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  791. def delete_client_role(self, client_role_id, role_name):
  792. """
  793. Delete a client role
  794. RoleRepresentation
  795. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  796. :param client_role_id: id of client (not client-id)
  797. :param role_name: roles name (not id!)
  798. """
  799. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  800. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  801. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  802. def assign_client_role(self, user_id, client_id, roles):
  803. """
  804. Assign a client role to a user
  805. :param user_id: id of user
  806. :param client_id: id of client (not client-id)
  807. :param roles: roles list or role (use RoleRepresentation)
  808. :return Keycloak server response
  809. """
  810. payload = roles if isinstance(roles, list) else [roles]
  811. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  812. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  813. data=json.dumps(payload))
  814. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  815. def get_client_role_members(self, client_id, role_name, **query):
  816. """
  817. Get members by client role .
  818. :param client_id: The client id
  819. :param role_name: the name of role to be queried.
  820. :param query: Additional query parameters ( see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_clients_resource)
  821. :return: Keycloak server response (UserRepresentation)
  822. """
  823. params_path = {"realm-name": self.realm_name, "id":client_id, "role-name":role_name}
  824. return self.__fetch_all(URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path) , query)
  825. def create_realm_role(self, payload, skip_exists=False):
  826. """
  827. Create a new role for the realm or client
  828. :param payload: The role (use RoleRepresentation)
  829. :param skip_exists: If true then do not raise an error if realm role already exists
  830. :return Keycloak server response
  831. """
  832. params_path = {"realm-name": self.realm_name}
  833. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  834. data=json.dumps(payload))
  835. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  836. def get_realm_role(self, role_name):
  837. """
  838. Get realm role by role name
  839. :param role_name: role's name, not id!
  840. RoleRepresentation
  841. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  842. :return: role_id
  843. """
  844. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  845. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  846. return raise_error_from_response(data_raw, KeycloakGetError)
  847. def update_realm_role(self, role_name, payload):
  848. """
  849. Update a role for the realm by name
  850. :param role_name: The name of the role to be updated
  851. :param payload: The role (use RoleRepresentation)
  852. :return Keycloak server response
  853. """
  854. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  855. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  856. data=json.dumps(payload))
  857. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  858. def delete_realm_role(self, role_name):
  859. """
  860. Delete a role for the realm by name
  861. :param payload: The role name {'role-name':'name-of-the-role'}
  862. :return Keycloak server response
  863. """
  864. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  865. data_raw = self.connection.raw_delete(
  866. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  867. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  868. def add_composite_realm_roles_to_role(self, role_name, roles):
  869. """
  870. Add composite roles to the role
  871. :param role_name: The name of the role
  872. :param roles: roles list or role (use RoleRepresentation) to be updated
  873. :return Keycloak server response
  874. """
  875. payload = roles if isinstance(roles, list) else [roles]
  876. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  877. data_raw = self.raw_post(
  878. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  879. data=json.dumps(payload))
  880. return raise_error_from_response(data_raw, KeycloakGetError,
  881. expected_codes=[204])
  882. def remove_composite_realm_roles_to_role(self, role_name, roles):
  883. """
  884. Remove composite roles from the role
  885. :param role_name: The name of the role
  886. :param roles: roles list or role (use RoleRepresentation) to be removed
  887. :return Keycloak server response
  888. """
  889. payload = roles if isinstance(roles, list) else [roles]
  890. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  891. data_raw = self.raw_delete(
  892. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  893. data=json.dumps(payload))
  894. return raise_error_from_response(data_raw, KeycloakGetError,
  895. expected_codes=[204])
  896. def get_composite_realm_roles_of_role(self, role_name):
  897. """
  898. Get composite roles of the role
  899. :param role_name: The name of the role
  900. :return Keycloak server response (array RoleRepresentation)
  901. """
  902. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  903. data_raw = self.raw_get(
  904. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  905. return raise_error_from_response(data_raw, KeycloakGetError)
  906. def assign_realm_roles(self, user_id, client_id, roles):
  907. """
  908. Assign realm roles to a user
  909. :param user_id: id of user
  910. :param client_id: id of client containing role (not client-id)
  911. :param roles: roles list or role (use RoleRepresentation)
  912. :return Keycloak server response
  913. """
  914. payload = roles if isinstance(roles, list) else [roles]
  915. params_path = {"realm-name": self.realm_name, "id": user_id}
  916. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  917. data=json.dumps(payload))
  918. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  919. def get_realm_roles_of_user(self, user_id):
  920. """
  921. Get all realm roles for a user.
  922. :param user_id: id of user
  923. :return: Keycloak server response (array RoleRepresentation)
  924. """
  925. params_path = {"realm-name": self.realm_name, "id": user_id}
  926. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  927. return raise_error_from_response(data_raw, KeycloakGetError)
  928. def assign_group_realm_roles(self, group_id, roles):
  929. """
  930. Assign realm roles to a group
  931. :param group_id: id of groupp
  932. :param roles: roles list or role (use GroupRoleRepresentation)
  933. :return Keycloak server response
  934. """
  935. payload = roles if isinstance(roles, list) else [roles]
  936. params_path = {"realm-name": self.realm_name, "id": group_id}
  937. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  938. data=json.dumps(payload))
  939. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  940. def delete_group_realm_roles(self, group_id, roles):
  941. """
  942. Delete realm roles of a group
  943. :param group_id: id of group
  944. :param roles: roles list or role (use GroupRoleRepresentation)
  945. :return Keycloak server response
  946. """
  947. payload = roles if isinstance(roles, list) else [roles]
  948. params_path = {"realm-name": self.realm_name, "id": group_id}
  949. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  950. data=json.dumps(payload))
  951. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  952. def get_group_realm_roles(self, group_id):
  953. """
  954. Get all realm roles for a group.
  955. :param user_id: id of the group
  956. :return: Keycloak server response (array RoleRepresentation)
  957. """
  958. params_path = {"realm-name": self.realm_name, "id": group_id}
  959. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  960. return raise_error_from_response(data_raw, KeycloakGetError)
  961. def assign_group_client_roles(self, group_id, client_id, roles):
  962. """
  963. Assign client roles to a group
  964. :param group_id: id of group
  965. :param client_id: id of client (not client-id)
  966. :param roles: roles list or role (use GroupRoleRepresentation)
  967. :return Keycloak server response
  968. """
  969. payload = roles if isinstance(roles, list) else [roles]
  970. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  971. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  972. data=json.dumps(payload))
  973. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  974. def get_group_client_roles(self, group_id, client_id):
  975. """
  976. Get client roles of a group
  977. :param group_id: id of group
  978. :param client_id: id of client (not client-id)
  979. :return Keycloak server response
  980. """
  981. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  982. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  983. return raise_error_from_response(data_raw, KeycloakGetError)
  984. def delete_group_client_roles(self, group_id, client_id, roles):
  985. """
  986. Delete client roles of a group
  987. :param group_id: id of group
  988. :param client_id: id of client (not client-id)
  989. :param roles: roles list or role (use GroupRoleRepresentation)
  990. :return Keycloak server response (array RoleRepresentation)
  991. """
  992. payload = roles if isinstance(roles, list) else [roles]
  993. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  994. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  995. data=json.dumps(payload))
  996. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  997. def get_client_roles_of_user(self, user_id, client_id):
  998. """
  999. Get all client roles for a user.
  1000. :param user_id: id of user
  1001. :param client_id: id of client (not client-id)
  1002. :return: Keycloak server response (array RoleRepresentation)
  1003. """
  1004. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1005. def get_available_client_roles_of_user(self, user_id, client_id):
  1006. """
  1007. Get available client role-mappings for a user.
  1008. :param user_id: id of user
  1009. :param client_id: id of client (not client-id)
  1010. :return: Keycloak server response (array RoleRepresentation)
  1011. """
  1012. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1013. def get_composite_client_roles_of_user(self, user_id, client_id):
  1014. """
  1015. Get composite client role-mappings for a user.
  1016. :param user_id: id of user
  1017. :param client_id: id of client (not client-id)
  1018. :return: Keycloak server response (array RoleRepresentation)
  1019. """
  1020. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1021. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1022. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1023. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1024. return raise_error_from_response(data_raw, KeycloakGetError)
  1025. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1026. """
  1027. Delete client roles from a user.
  1028. :param user_id: id of user
  1029. :param client_id: id of client containing role (not client-id)
  1030. :param roles: roles list or role to delete (use RoleRepresentation)
  1031. :return: Keycloak server response
  1032. """
  1033. payload = roles if isinstance(roles, list) else [roles]
  1034. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1035. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1036. data=json.dumps(payload))
  1037. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1038. def get_authentication_flows(self):
  1039. """
  1040. Get authentication flows. Returns all flow details
  1041. AuthenticationFlowRepresentation
  1042. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1043. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1044. """
  1045. params_path = {"realm-name": self.realm_name}
  1046. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1047. return raise_error_from_response(data_raw, KeycloakGetError)
  1048. def get_authentication_flow_for_id(self, flow_id):
  1049. """
  1050. Get one authentication flow by it's id/alias. Returns all flow details
  1051. AuthenticationFlowRepresentation
  1052. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1053. :param flow_id: the id of a flow NOT it's alias
  1054. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1055. """
  1056. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1057. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1058. return raise_error_from_response(data_raw, KeycloakGetError)
  1059. def create_authentication_flow(self, payload, skip_exists=False):
  1060. """
  1061. Create a new authentication flow
  1062. AuthenticationFlowRepresentation
  1063. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1064. :param payload: AuthenticationFlowRepresentation
  1065. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1066. :return: Keycloak server response (RoleRepresentation)
  1067. """
  1068. params_path = {"realm-name": self.realm_name}
  1069. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1070. data=json.dumps(payload))
  1071. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1072. def copy_authentication_flow(self, payload, flow_alias):
  1073. """
  1074. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1075. :param payload: JSON containing 'newName' attribute
  1076. :param flow_alias: the flow alias
  1077. :return: Keycloak server response (RoleRepresentation)
  1078. """
  1079. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1080. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1081. data=json.dumps(payload))
  1082. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1083. def get_authentication_flow_executions(self, flow_alias):
  1084. """
  1085. Get authentication flow executions. Returns all execution steps
  1086. :param flow_alias: the flow alias
  1087. :return: Response(json)
  1088. """
  1089. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1090. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1091. return raise_error_from_response(data_raw, KeycloakGetError)
  1092. def update_authentication_flow_executions(self, payload, flow_alias):
  1093. """
  1094. Update an authentication flow execution
  1095. AuthenticationExecutionInfoRepresentation
  1096. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1097. :param payload: AuthenticationExecutionInfoRepresentation
  1098. :param flow_alias: The flow alias
  1099. :return: Keycloak server response
  1100. """
  1101. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1102. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1103. data=json.dumps(payload))
  1104. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1105. def create_authentication_flow_execution(self, payload, flow_alias):
  1106. """
  1107. Create an authentication flow execution
  1108. AuthenticationExecutionInfoRepresentation
  1109. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1110. :param payload: AuthenticationExecutionInfoRepresentation
  1111. :param flow_alias: The flow alias
  1112. :return: Keycloak server response
  1113. """
  1114. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1115. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1116. data=json.dumps(payload))
  1117. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1118. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1119. """
  1120. Create a new sub authentication flow for a given authentication flow
  1121. AuthenticationFlowRepresentation
  1122. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1123. :param payload: AuthenticationFlowRepresentation
  1124. :param flow_alias: The flow alias
  1125. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1126. :return: Keycloak server response (RoleRepresentation)
  1127. """
  1128. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1129. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1130. data=json.dumps(payload))
  1131. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1132. def get_authenticator_config(self, config_id):
  1133. """
  1134. Get authenticator configuration. Returns all configuration details.
  1135. :param config_id: Authenticator config id
  1136. :return: Response(json)
  1137. """
  1138. params_path = {"realm-name": self.realm_name, "id": config_id}
  1139. data_raw = self.raw_get(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1140. return raise_error_from_response(data_raw, KeycloakGetError)
  1141. def update_authenticator_config(self, payload, config_id):
  1142. """
  1143. Update an authenticator configuration.
  1144. AuthenticatorConfigRepresentation
  1145. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticatorconfigrepresentation
  1146. :param payload: AuthenticatorConfigRepresentation
  1147. :param config_id: Authenticator config id
  1148. :return: Response(json)
  1149. """
  1150. params_path = {"realm-name": self.realm_name, "id": config_id}
  1151. data_raw = self.raw_put(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1152. data=json.dumps(payload))
  1153. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1154. def delete_authenticator_config(self, config_id):
  1155. """
  1156. Delete a authenticator configuration.
  1157. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource
  1158. :param config_id: Authenticator config id
  1159. :return: Keycloak server Response
  1160. """
  1161. params_path = {"realm-name": self.realm_name, "id": config_id}
  1162. data_raw = self.raw_delete(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1163. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1164. def sync_users(self, storage_id, action):
  1165. """
  1166. Function to trigger user sync from provider
  1167. :param storage_id: The id of the user storage provider
  1168. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1169. :return:
  1170. """
  1171. data = {'action': action}
  1172. params_query = {"action": action}
  1173. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1174. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1175. data=json.dumps(data), **params_query)
  1176. return raise_error_from_response(data_raw, KeycloakGetError)
  1177. def get_client_scopes(self):
  1178. """
  1179. Get representation of the client scopes for the realm where we are connected to
  1180. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1181. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1182. """
  1183. params_path = {"realm-name": self.realm_name}
  1184. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1185. return raise_error_from_response(data_raw, KeycloakGetError)
  1186. def get_client_scope(self, client_scope_id):
  1187. """
  1188. Get representation of the client scopes for the realm where we are connected to
  1189. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1190. :param client_scope_id: The id of the client scope
  1191. :return: Keycloak server response (ClientScopeRepresentation)
  1192. """
  1193. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1194. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1195. return raise_error_from_response(data_raw, KeycloakGetError)
  1196. def create_client_scope(self, payload, skip_exists=False):
  1197. """
  1198. Create a client scope
  1199. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1200. :param payload: ClientScopeRepresentation
  1201. :param skip_exists: If true then do not raise an error if client scope already exists
  1202. :return: Keycloak server response (ClientScopeRepresentation)
  1203. """
  1204. params_path = {"realm-name": self.realm_name}
  1205. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1206. data=json.dumps(payload))
  1207. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1208. def update_client_scope(self, client_scope_id, payload):
  1209. """
  1210. Update a client scope
  1211. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_client_scopes_resource
  1212. :param client_scope_id: The id of the client scope
  1213. :param payload: ClientScopeRepresentation
  1214. :return: Keycloak server response (ClientScopeRepresentation)
  1215. """
  1216. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1217. data_raw = self.raw_put(URL_ADMIN_CLIENT_SCOPE.format(**params_path),
  1218. data=json.dumps(payload))
  1219. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1220. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1221. """
  1222. Add a mapper to a client scope
  1223. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1224. :param client_scope_id: The id of the client scope
  1225. :param payload: ProtocolMapperRepresentation
  1226. :return: Keycloak server Response
  1227. """
  1228. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1229. data_raw = self.raw_post(
  1230. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1231. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1232. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1233. """
  1234. Delete a mapper from a client scope
  1235. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1236. :param client_scope_id: The id of the client scope
  1237. :param payload: ProtocolMapperRepresentation
  1238. :return: Keycloak server Response
  1239. """
  1240. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1241. "protocol-mapper-id": protocol_mppaer_id}
  1242. data_raw = self.raw_delete(
  1243. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1244. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1245. def add_mapper_to_client(self, client_id, payload):
  1246. """
  1247. Add a mapper to a client
  1248. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1249. :param client_id: The id of the client
  1250. :param payload: ProtocolMapperRepresentation
  1251. :return: Keycloak server Response
  1252. """
  1253. params_path = {"realm-name": self.realm_name, "id": client_id}
  1254. data_raw = self.raw_post(
  1255. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1256. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1257. def generate_client_secrets(self, client_id):
  1258. """
  1259. Generate a new secret for the client
  1260. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1261. :param client_id: id of client (not client-id)
  1262. :return: Keycloak server response (ClientRepresentation)
  1263. """
  1264. params_path = {"realm-name": self.realm_name, "id": client_id}
  1265. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1266. return raise_error_from_response(data_raw, KeycloakGetError)
  1267. def get_client_secrets(self, client_id):
  1268. """
  1269. Get representation of the client secrets
  1270. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1271. :param client_id: id of client (not client-id)
  1272. :return: Keycloak server response (ClientRepresentation)
  1273. """
  1274. params_path = {"realm-name": self.realm_name, "id": client_id}
  1275. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1276. return raise_error_from_response(data_raw, KeycloakGetError)
  1277. def get_components(self, query=None):
  1278. """
  1279. Return a list of components, filtered according to query parameters
  1280. ComponentRepresentation
  1281. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1282. :param query: Query parameters (optional)
  1283. :return: components list
  1284. """
  1285. params_path = {"realm-name": self.realm_name}
  1286. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1287. data=None, **query)
  1288. return raise_error_from_response(data_raw, KeycloakGetError)
  1289. def create_component(self, payload):
  1290. """
  1291. Create a new component.
  1292. ComponentRepresentation
  1293. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1294. :param payload: ComponentRepresentation
  1295. :return: UserRepresentation
  1296. """
  1297. params_path = {"realm-name": self.realm_name}
  1298. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1299. data=json.dumps(payload))
  1300. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1301. def get_component(self, component_id):
  1302. """
  1303. Get representation of the component
  1304. :param component_id: Component id
  1305. ComponentRepresentation
  1306. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1307. :return: ComponentRepresentation
  1308. """
  1309. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1310. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1311. return raise_error_from_response(data_raw, KeycloakGetError)
  1312. def update_component(self, component_id, payload):
  1313. """
  1314. Update the component
  1315. :param component_id: Component id
  1316. :param payload: ComponentRepresentation
  1317. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1318. :return: Http response
  1319. """
  1320. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1321. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1322. data=json.dumps(payload))
  1323. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1324. def delete_component(self, component_id):
  1325. """
  1326. Delete the component
  1327. :param component_id: Component id
  1328. :return: Http response
  1329. """
  1330. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1331. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1332. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1333. def get_keys(self):
  1334. """
  1335. Return a list of keys, filtered according to query parameters
  1336. KeysMetadataRepresentation
  1337. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1338. :return: keys list
  1339. """
  1340. params_path = {"realm-name": self.realm_name}
  1341. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1342. data=None)
  1343. return raise_error_from_response(data_raw, KeycloakGetError)
  1344. def raw_get(self, *args, **kwargs):
  1345. """
  1346. Calls connection.raw_get.
  1347. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1348. and try *get* once more.
  1349. """
  1350. r = self.connection.raw_get(*args, **kwargs)
  1351. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1352. self.refresh_token()
  1353. return self.connection.raw_get(*args, **kwargs)
  1354. return r
  1355. def raw_post(self, *args, **kwargs):
  1356. """
  1357. Calls connection.raw_post.
  1358. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1359. and try *post* once more.
  1360. """
  1361. r = self.connection.raw_post(*args, **kwargs)
  1362. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1363. self.refresh_token()
  1364. return self.connection.raw_post(*args, **kwargs)
  1365. return r
  1366. def raw_put(self, *args, **kwargs):
  1367. """
  1368. Calls connection.raw_put.
  1369. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1370. and try *put* once more.
  1371. """
  1372. r = self.connection.raw_put(*args, **kwargs)
  1373. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1374. self.refresh_token()
  1375. return self.connection.raw_put(*args, **kwargs)
  1376. return r
  1377. def raw_delete(self, *args, **kwargs):
  1378. """
  1379. Calls connection.raw_delete.
  1380. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1381. and try *delete* once more.
  1382. """
  1383. r = self.connection.raw_delete(*args, **kwargs)
  1384. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1385. self.refresh_token()
  1386. return self.connection.raw_delete(*args, **kwargs)
  1387. return r
  1388. def get_token(self):
  1389. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1390. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1391. client_secret_key=self.client_secret_key,
  1392. custom_headers=self.custom_headers)
  1393. grant_type = ["password"]
  1394. if self.client_secret_key:
  1395. grant_type = ["client_credentials"]
  1396. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1397. headers = {
  1398. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1399. 'Content-Type': 'application/json'
  1400. }
  1401. if self.custom_headers is not None:
  1402. # merge custom headers to main headers
  1403. headers.update(self.custom_headers)
  1404. self._connection = ConnectionManager(base_url=self.server_url,
  1405. headers=headers,
  1406. timeout=60,
  1407. verify=self.verify)
  1408. def refresh_token(self):
  1409. refresh_token = self.token.get('refresh_token')
  1410. try:
  1411. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1412. except KeycloakGetError as e:
  1413. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1414. b'Token is not active' in e.response_body):
  1415. self.get_token()
  1416. else:
  1417. raise
  1418. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))
  1419. def get_client_all_sessions(self, client_id):
  1420. """
  1421. Get sessions associated with the client
  1422. :param client_id: id of client
  1423. UserSessionRepresentation
  1424. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  1425. :return: UserSessionRepresentation
  1426. """
  1427. params_path = {"realm-name": self.realm_name, "client-id": client_id}
  1428. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  1429. return raise_error_from_response(data_raw, KeycloakGetError)