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.

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