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.

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