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.

1962 lines
77 KiB

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