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.

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