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.

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