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.

1526 lines
58 KiB

7 years ago
6 years ago
6 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
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
4 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from builtins import isinstance
  27. from typing import List, Iterable
  28. from keycloak.urls_patterns import URL_ADMIN_GROUPS_REALM_ROLES, \
  29. URL_ADMIN_GET_GROUPS_REALM_ROLES, URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GROUPS_CLIENT_ROLES, \
  30. URL_ADMIN_GET_GROUPS_REALM_ROLES, URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, \
  31. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE
  32. from .connection import ConnectionManager
  33. from .exceptions import raise_error_from_response, KeycloakGetError
  34. from .keycloak_openid import KeycloakOpenID
  35. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  36. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, \
  37. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  38. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  39. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  40. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  41. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, \
  42. URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  43. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  44. URL_ADMIN_USER_REALM_ROLES, URL_ADMIN_REALM, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS, \
  45. URL_ADMIN_USER_FEDERATED_IDENTITY, URL_ADMIN_USER_FEDERATED_IDENTITIES
  46. class KeycloakAdmin:
  47. PAGE_SIZE = 100
  48. _server_url = None
  49. _username = None
  50. _password = None
  51. _realm_name = None
  52. _client_id = None
  53. _verify = None
  54. _client_secret_key = None
  55. _auto_refresh_token = None
  56. _connection = None
  57. _token = None
  58. _custom_headers = None
  59. _user_realm_name = None
  60. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  61. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  62. """
  63. :param server_url: Keycloak server url
  64. :param username: admin username
  65. :param password: admin password
  66. :param realm_name: realm name
  67. :param client_id: client id
  68. :param verify: True if want check connection SSL
  69. :param client_secret_key: client secret key
  70. :param custom_headers: dict of custom header to pass to each HTML request
  71. :param user_realm_name: The realm name of the user, if different from realm_name
  72. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  73. """
  74. self.server_url = server_url
  75. self.username = username
  76. self.password = password
  77. self.realm_name = realm_name
  78. self.client_id = client_id
  79. self.verify = verify
  80. self.client_secret_key = client_secret_key
  81. self.auto_refresh_token = auto_refresh_token or []
  82. self.user_realm_name = user_realm_name
  83. self.custom_headers = custom_headers
  84. # Get token Admin
  85. self.get_token()
  86. @property
  87. def server_url(self):
  88. return self._server_url
  89. @server_url.setter
  90. def server_url(self, value):
  91. self._server_url = value
  92. @property
  93. def realm_name(self):
  94. return self._realm_name
  95. @realm_name.setter
  96. def realm_name(self, value):
  97. self._realm_name = value
  98. @property
  99. def connection(self):
  100. return self._connection
  101. @connection.setter
  102. def connection(self, value):
  103. self._connection = value
  104. @property
  105. def client_id(self):
  106. return self._client_id
  107. @client_id.setter
  108. def client_id(self, value):
  109. self._client_id = value
  110. @property
  111. def client_secret_key(self):
  112. return self._client_secret_key
  113. @client_secret_key.setter
  114. def client_secret_key(self, value):
  115. self._client_secret_key = value
  116. @property
  117. def verify(self):
  118. return self._verify
  119. @verify.setter
  120. def verify(self, value):
  121. self._verify = value
  122. @property
  123. def username(self):
  124. return self._username
  125. @username.setter
  126. def username(self, value):
  127. self._username = value
  128. @property
  129. def password(self):
  130. return self._password
  131. @password.setter
  132. def password(self, value):
  133. self._password = value
  134. @property
  135. def token(self):
  136. return self._token
  137. @token.setter
  138. def token(self, value):
  139. self._token = value
  140. @property
  141. def auto_refresh_token(self):
  142. return self._auto_refresh_token
  143. @property
  144. def user_realm_name(self):
  145. return self._user_realm_name
  146. @user_realm_name.setter
  147. def user_realm_name(self, value):
  148. self._user_realm_name = value
  149. @property
  150. def custom_headers(self):
  151. return self._custom_headers
  152. @custom_headers.setter
  153. def custom_headers(self, value):
  154. self._custom_headers = value
  155. @auto_refresh_token.setter
  156. def auto_refresh_token(self, value):
  157. allowed_methods = {'get', 'post', 'put', 'delete'}
  158. if not isinstance(value, Iterable):
  159. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  160. if not all(method in allowed_methods for method in value):
  161. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  162. self._auto_refresh_token = value
  163. def __fetch_all(self, url, query=None):
  164. '''Wrapper function to paginate GET requests
  165. :param url: The url on which the query is executed
  166. :param query: Existing query parameters (optional)
  167. :return: Combined results of paginated queries
  168. '''
  169. results = []
  170. # initalize query if it was called with None
  171. if not query:
  172. query = {}
  173. page = 0
  174. query['max'] = self.PAGE_SIZE
  175. # fetch until we can
  176. while True:
  177. query['first'] = page*self.PAGE_SIZE
  178. partial_results = raise_error_from_response(
  179. self.raw_get(url, **query),
  180. KeycloakGetError)
  181. if not partial_results:
  182. break
  183. results.extend(partial_results)
  184. page += 1
  185. return results
  186. def import_realm(self, payload):
  187. """
  188. Import a new realm from a RealmRepresentation. Realm name must be unique.
  189. RealmRepresentation
  190. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  191. :param payload: RealmRepresentation
  192. :return: RealmRepresentation
  193. """
  194. data_raw = self.raw_post(URL_ADMIN_REALMS,
  195. data=json.dumps(payload))
  196. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  197. def get_realms(self):
  198. """
  199. Lists all realms in Keycloak deployment
  200. :return: realms list
  201. """
  202. data_raw = self.raw_get(URL_ADMIN_REALMS)
  203. return raise_error_from_response(data_raw, KeycloakGetError)
  204. def create_realm(self, payload, skip_exists=False):
  205. """
  206. Create a realm
  207. RealmRepresentation:
  208. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  209. :param payload: RealmRepresentation
  210. :param skip_exists: Skip if Realm already exist.
  211. :return: Keycloak server response (RealmRepresentation)
  212. """
  213. data_raw = self.raw_post(URL_ADMIN_REALMS,
  214. data=json.dumps(payload))
  215. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  216. def update_realm(self, realm_name, payload):
  217. """
  218. Update a realm. This wil only update top level attributes and will ignore any user,
  219. role, or client information in the payload.
  220. RealmRepresentation:
  221. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  222. :param realm_name: Realm name (not the realm id)
  223. :param payload: RealmRepresentation
  224. :return: Http response
  225. """
  226. params_path = {"realm-name": realm_name}
  227. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  228. data=json.dumps(payload))
  229. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  230. def delete_realm(self, realm_name):
  231. """
  232. Delete a realm
  233. :param realm_name: Realm name (not the realm id)
  234. :return: Http response
  235. """
  236. params_path = {"realm-name": realm_name}
  237. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  238. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  239. def get_users(self, query=None):
  240. """
  241. Return a list of users, filtered according to query parameters
  242. UserRepresentation
  243. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  244. :param query: Query parameters (optional)
  245. :return: users list
  246. """
  247. params_path = {"realm-name": self.realm_name}
  248. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  249. def get_idps(self):
  250. """
  251. Returns a list of ID Providers,
  252. IdentityProviderRepresentation
  253. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  254. :return: array IdentityProviderRepresentation
  255. """
  256. params_path = {"realm-name": self.realm_name}
  257. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  258. return raise_error_from_response(data_raw, KeycloakGetError)
  259. def create_user(self, payload):
  260. """
  261. Create a new user. Username must be unique
  262. UserRepresentation
  263. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  264. :param payload: UserRepresentation
  265. :return: UserRepresentation
  266. """
  267. params_path = {"realm-name": self.realm_name}
  268. exists = self.get_user_id(username=payload['username'])
  269. if exists is not None:
  270. return str(exists)
  271. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  272. data=json.dumps(payload))
  273. raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  274. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  275. return data_raw.headers['Location'][_last_slash_idx + 1:]
  276. def users_count(self):
  277. """
  278. User counter
  279. :return: counter
  280. """
  281. params_path = {"realm-name": self.realm_name}
  282. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  283. return raise_error_from_response(data_raw, KeycloakGetError)
  284. def get_user_id(self, username):
  285. """
  286. Get internal keycloak user id from username
  287. This is required for further actions against this user.
  288. UserRepresentation
  289. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  290. :param username: id in UserRepresentation
  291. :return: user_id
  292. """
  293. users = self.get_users(query={"search": username})
  294. return next((user["id"] for user in users if user["username"] == username), None)
  295. def get_user(self, user_id):
  296. """
  297. Get representation of the user
  298. :param user_id: User id
  299. UserRepresentation
  300. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  301. :return: UserRepresentation
  302. """
  303. params_path = {"realm-name": self.realm_name, "id": user_id}
  304. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  305. return raise_error_from_response(data_raw, KeycloakGetError)
  306. def get_user_groups(self, user_id):
  307. """
  308. Returns a list of groups of which the user is a member
  309. :param user_id: User id
  310. :return: user groups list
  311. """
  312. params_path = {"realm-name": self.realm_name, "id": user_id}
  313. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  314. return raise_error_from_response(data_raw, KeycloakGetError)
  315. def update_user(self, user_id, payload):
  316. """
  317. Update the user
  318. :param user_id: User id
  319. :param payload: UserRepresentation
  320. :return: Http response
  321. """
  322. params_path = {"realm-name": self.realm_name, "id": user_id}
  323. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  324. data=json.dumps(payload))
  325. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  326. def delete_user(self, user_id):
  327. """
  328. Delete the user
  329. :param user_id: User id
  330. :return: Http response
  331. """
  332. params_path = {"realm-name": self.realm_name, "id": user_id}
  333. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  334. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  335. def set_user_password(self, user_id, password, temporary=True):
  336. """
  337. Set up a password for the user. If temporary is True, the user will have to reset
  338. the temporary password next time they log in.
  339. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  340. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  341. :param user_id: User id
  342. :param password: New password
  343. :param temporary: True if password is temporary
  344. :return:
  345. """
  346. payload = {"type": "password", "temporary": temporary, "value": password}
  347. params_path = {"realm-name": self.realm_name, "id": user_id}
  348. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  349. data=json.dumps(payload))
  350. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  351. def consents_user(self, user_id):
  352. """
  353. Get consents granted by the user
  354. :param user_id: User id
  355. :return: consents
  356. """
  357. params_path = {"realm-name": self.realm_name, "id": user_id}
  358. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  359. return raise_error_from_response(data_raw, KeycloakGetError)
  360. def get_user_social_logins(self, user_id):
  361. """
  362. Returns a list of federated identities/social logins of which the user has been associated with
  363. :param user_id: User id
  364. :return: federated identities list
  365. """
  366. params_path = {"realm-name": self.realm_name, "id": user_id}
  367. data_raw = self.raw_get(URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path))
  368. return raise_error_from_response(data_raw, KeycloakGetError)
  369. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  370. """
  371. Add a federated identity / social login provider to the user
  372. :param user_id: User id
  373. :param provider_id: Social login provider id
  374. :param provider_userid: userid specified by the provider
  375. :param provider_username: username specified by the provider
  376. :return:
  377. """
  378. payload = {"identityProvider": provider_id, "userId": provider_userid, "userName": provider_username}
  379. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  380. data_raw = self.raw_post(URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path), data=json.dumps(payload))
  381. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  382. """
  383. Send an update account email to the user. An email contains a
  384. link the user can click to perform a set of required actions.
  385. :param user_id: User id
  386. :param payload: A list of actions for the user to complete
  387. :param client_id: Client id (optional)
  388. :param lifespan: Number of seconds after which the generated token expires (optional)
  389. :param redirect_uri: The redirect uri (optional)
  390. :return:
  391. """
  392. params_path = {"realm-name": self.realm_name, "id": user_id}
  393. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  394. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  395. data=payload, **params_query)
  396. return raise_error_from_response(data_raw, KeycloakGetError)
  397. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  398. """
  399. Send a update account email to the user An email contains a
  400. link the user can click to perform a set of required actions.
  401. :param user_id: User id
  402. :param client_id: Client id (optional)
  403. :param redirect_uri: Redirect uri (optional)
  404. :return:
  405. """
  406. params_path = {"realm-name": self.realm_name, "id": user_id}
  407. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  408. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  409. data={}, **params_query)
  410. return raise_error_from_response(data_raw, KeycloakGetError)
  411. def get_sessions(self, user_id):
  412. """
  413. Get sessions associated with the user
  414. :param user_id: id of user
  415. UserSessionRepresentation
  416. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  417. :return: UserSessionRepresentation
  418. """
  419. params_path = {"realm-name": self.realm_name, "id": user_id}
  420. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  421. return raise_error_from_response(data_raw, KeycloakGetError)
  422. def get_server_info(self):
  423. """
  424. Get themes, social providers, auth providers, and event listeners available on this server
  425. ServerInfoRepresentation
  426. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  427. :return: ServerInfoRepresentation
  428. """
  429. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  430. return raise_error_from_response(data_raw, KeycloakGetError)
  431. def get_groups(self):
  432. """
  433. Returns a list of groups belonging to the realm
  434. GroupRepresentation
  435. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  436. :return: array GroupRepresentation
  437. """
  438. params_path = {"realm-name": self.realm_name}
  439. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  440. def get_group(self, group_id):
  441. """
  442. Get group by id. Returns full group details
  443. GroupRepresentation
  444. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  445. :param group_id: The group id
  446. :return: Keycloak server response (GroupRepresentation)
  447. """
  448. params_path = {"realm-name": self.realm_name, "id": group_id}
  449. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  450. return raise_error_from_response(data_raw, KeycloakGetError)
  451. def get_subgroups(self, group, path):
  452. """
  453. Utility function to iterate through nested group structures
  454. GroupRepresentation
  455. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  456. :param name: group (GroupRepresentation)
  457. :param path: group path (string)
  458. :return: Keycloak server response (GroupRepresentation)
  459. """
  460. for subgroup in group["subGroups"]:
  461. if subgroup['path'] == path:
  462. return subgroup
  463. elif subgroup["subGroups"]:
  464. for subgroup in group["subGroups"]:
  465. result = self.get_subgroups(subgroup, path)
  466. if result:
  467. return result
  468. # went through the tree without hits
  469. return None
  470. def get_group_members(self, group_id, **query):
  471. """
  472. Get members by group id. Returns group members
  473. GroupRepresentation
  474. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  475. :param group_id: The group id
  476. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  477. :return: Keycloak server response (UserRepresentation)
  478. """
  479. params_path = {"realm-name": self.realm_name, "id": group_id}
  480. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  481. def get_group_by_path(self, path, search_in_subgroups=False):
  482. """
  483. Get group id based on name or path.
  484. A straight name or path match with a top-level group will return first.
  485. Subgroups are traversed, the first to match path (or name with path) is returned.
  486. GroupRepresentation
  487. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  488. :param path: group path
  489. :param search_in_subgroups: True if want search in the subgroups
  490. :return: Keycloak server response (GroupRepresentation)
  491. """
  492. groups = self.get_groups()
  493. # TODO: Review this code is necessary
  494. for group in groups:
  495. if group['path'] == path:
  496. return group
  497. elif search_in_subgroups and group["subGroups"]:
  498. for group in group["subGroups"]:
  499. if group['path'] == path:
  500. return group
  501. res = self.get_subgroups(group, path)
  502. if res != None:
  503. return res
  504. return None
  505. def create_group(self, payload, parent=None, skip_exists=False):
  506. """
  507. Creates a group in the Realm
  508. :param payload: GroupRepresentation
  509. :param parent: parent group's id. Required to create a sub-group.
  510. :param skip_exists: If true then do not raise an error if it already exists
  511. GroupRepresentation
  512. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  513. :return: Http response
  514. """
  515. if parent is None:
  516. params_path = {"realm-name": self.realm_name}
  517. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  518. data=json.dumps(payload))
  519. else:
  520. params_path = {"realm-name": self.realm_name, "id": parent, }
  521. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  522. data=json.dumps(payload))
  523. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  524. def update_group(self, group_id, payload):
  525. """
  526. Update group, ignores subgroups.
  527. :param group_id: id of group
  528. :param payload: GroupRepresentation with updated information.
  529. GroupRepresentation
  530. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  531. :return: Http response
  532. """
  533. params_path = {"realm-name": self.realm_name, "id": group_id}
  534. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  535. data=json.dumps(payload))
  536. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  537. def group_set_permissions(self, group_id, enabled=True):
  538. """
  539. Enable/Disable permissions for a group. Cannot delete group if disabled
  540. :param group_id: id of group
  541. :param enabled: boolean
  542. :return: Keycloak server response
  543. """
  544. params_path = {"realm-name": self.realm_name, "id": group_id}
  545. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  546. data=json.dumps({"enabled": enabled}))
  547. return raise_error_from_response(data_raw, KeycloakGetError)
  548. def group_user_add(self, user_id, group_id):
  549. """
  550. Add user to group (user_id and group_id)
  551. :param user_id: id of user
  552. :param group_id: id of group to add to
  553. :return: Keycloak server response
  554. """
  555. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  556. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  557. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  558. def group_user_remove(self, user_id, group_id):
  559. """
  560. Remove user from group (user_id and group_id)
  561. :param user_id: id of user
  562. :param group_id: id of group to remove from
  563. :return: Keycloak server response
  564. """
  565. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  566. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  567. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  568. def delete_group(self, group_id):
  569. """
  570. Deletes a group in the Realm
  571. :param group_id: id of group to delete
  572. :return: Keycloak server response
  573. """
  574. params_path = {"realm-name": self.realm_name, "id": group_id}
  575. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  576. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  577. def get_clients(self):
  578. """
  579. Returns a list of clients belonging to the realm
  580. ClientRepresentation
  581. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  582. :return: Keycloak server response (ClientRepresentation)
  583. """
  584. params_path = {"realm-name": self.realm_name}
  585. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  586. return raise_error_from_response(data_raw, KeycloakGetError)
  587. def get_client(self, client_id):
  588. """
  589. Get representation of the client
  590. ClientRepresentation
  591. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  592. :param client_id: id of client (not client-id)
  593. :return: Keycloak server response (ClientRepresentation)
  594. """
  595. params_path = {"realm-name": self.realm_name, "id": client_id}
  596. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  597. return raise_error_from_response(data_raw, KeycloakGetError)
  598. def get_client_id(self, client_name):
  599. """
  600. Get internal keycloak client id from client-id.
  601. This is required for further actions against this client.
  602. :param client_name: name in ClientRepresentation
  603. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  604. :return: client_id (uuid as string)
  605. """
  606. clients = self.get_clients()
  607. for client in clients:
  608. if client_name == client.get('name') or client_name == client.get('clientId'):
  609. return client["id"]
  610. return None
  611. def get_client_authz_settings(self, client_id):
  612. """
  613. Get authorization json from client.
  614. :param client_id: id in ClientRepresentation
  615. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  616. :return: Keycloak server response
  617. """
  618. params_path = {"realm-name": self.realm_name, "id": client_id}
  619. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  620. return data_raw
  621. def get_client_authz_resources(self, client_id):
  622. """
  623. Get resources from client.
  624. :param client_id: id in ClientRepresentation
  625. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  626. :return: Keycloak server response
  627. """
  628. params_path = {"realm-name": self.realm_name, "id": client_id}
  629. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  630. return data_raw
  631. def create_client(self, payload, skip_exists=False):
  632. """
  633. Create a client
  634. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  635. :param skip_exists: If true then do not raise an error if client already exists
  636. :param payload: ClientRepresentation
  637. :return: Keycloak server response (UserRepresentation)
  638. """
  639. params_path = {"realm-name": self.realm_name}
  640. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  641. data=json.dumps(payload))
  642. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  643. def update_client(self, client_id, payload):
  644. """
  645. Update a client
  646. :param client_id: Client id
  647. :param payload: ClientRepresentation
  648. :return: Http response
  649. """
  650. params_path = {"realm-name": self.realm_name, "id": client_id}
  651. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  652. data=json.dumps(payload))
  653. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  654. def delete_client(self, client_id):
  655. """
  656. Get representation of the client
  657. ClientRepresentation
  658. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  659. :param client_id: keycloak client id (not oauth client-id)
  660. :return: Keycloak server response (ClientRepresentation)
  661. """
  662. params_path = {"realm-name": self.realm_name, "id": client_id}
  663. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  664. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  665. def get_realm_roles(self):
  666. """
  667. Get all roles for the realm or client
  668. RoleRepresentation
  669. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  670. :return: Keycloak server response (RoleRepresentation)
  671. """
  672. params_path = {"realm-name": self.realm_name}
  673. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  674. return raise_error_from_response(data_raw, KeycloakGetError)
  675. def get_client_roles(self, client_id):
  676. """
  677. Get all roles for the client
  678. :param client_id: id of client (not client-id)
  679. RoleRepresentation
  680. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  681. :return: Keycloak server response (RoleRepresentation)
  682. """
  683. params_path = {"realm-name": self.realm_name, "id": client_id}
  684. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  685. return raise_error_from_response(data_raw, KeycloakGetError)
  686. def get_client_role(self, client_id, role_name):
  687. """
  688. Get client role id by name
  689. This is required for further actions with this role.
  690. :param client_id: id of client (not client-id)
  691. :param role_name: roles name (not id!)
  692. RoleRepresentation
  693. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  694. :return: role_id
  695. """
  696. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  697. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  698. return raise_error_from_response(data_raw, KeycloakGetError)
  699. def get_client_role_id(self, client_id, role_name):
  700. """
  701. Warning: Deprecated
  702. Get client role id by name
  703. This is required for further actions with this role.
  704. :param client_id: id of client (not client-id)
  705. :param role_name: roles name (not id!)
  706. RoleRepresentation
  707. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  708. :return: role_id
  709. """
  710. role = self.get_client_role(client_id, role_name)
  711. return role.get("id")
  712. def create_client_role(self, client_role_id, payload, skip_exists=False):
  713. """
  714. Create a client role
  715. RoleRepresentation
  716. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  717. :param client_role_id: id of client (not client-id)
  718. :param payload: RoleRepresentation
  719. :param skip_exists: If true then do not raise an error if client role already exists
  720. :return: Keycloak server response (RoleRepresentation)
  721. """
  722. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  723. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  724. data=json.dumps(payload))
  725. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  726. def delete_client_role(self, client_role_id, role_name):
  727. """
  728. Delete a client role
  729. RoleRepresentation
  730. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  731. :param client_role_id: id of client (not client-id)
  732. :param role_name: roles name (not id!)
  733. """
  734. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  735. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  736. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  737. def assign_client_role(self, user_id, client_id, roles):
  738. """
  739. Assign a client role to a user
  740. :param user_id: id of user
  741. :param client_id: id of client (not client-id)
  742. :param roles: roles list or role (use RoleRepresentation)
  743. :return Keycloak server response
  744. """
  745. payload = roles if isinstance(roles, list) else [roles]
  746. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  747. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  748. data=json.dumps(payload))
  749. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  750. def create_realm_role(self, payload, skip_exists=False):
  751. """
  752. Create a new role for the realm or client
  753. :param payload: The role (use RoleRepresentation)
  754. :param skip_exists: If true then do not raise an error if realm role already exists
  755. :return Keycloak server response
  756. """
  757. params_path = {"realm-name": self.realm_name}
  758. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  759. data=json.dumps(payload))
  760. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  761. def update_realm_role(self, role_name, payload):
  762. """
  763. Update a role for the realm by name
  764. :param role_name: The name of the role to be updated
  765. :param payload: The role (use RoleRepresentation)
  766. :return Keycloak server response
  767. """
  768. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  769. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  770. data=json.dumps(payload))
  771. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  772. def delete_realm_role(self, role_name):
  773. """
  774. Delete a role for the realm by name
  775. :param payload: The role name {'role-name':'name-of-the-role'}
  776. :return Keycloak server response
  777. """
  778. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  779. data_raw = self.connection.raw_delete(
  780. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  781. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  782. def add_composite_realm_roles_to_role(self, role_name, roles):
  783. """
  784. Add composite roles to the role
  785. :param role_name: The name of the role
  786. :param roles: roles list or role (use RoleRepresentation) to be updated
  787. :return Keycloak server response
  788. """
  789. payload = roles if isinstance(roles, list) else [roles]
  790. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  791. data_raw = self.raw_post(
  792. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  793. data=json.dumps(payload))
  794. return raise_error_from_response(data_raw, KeycloakGetError,
  795. expected_codes=[204])
  796. def remove_composite_realm_roles_to_role(self, role_name, roles):
  797. """
  798. Remove composite roles from the role
  799. :param role_name: The name of the role
  800. :param roles: roles list or role (use RoleRepresentation) to be removed
  801. :return Keycloak server response
  802. """
  803. payload = roles if isinstance(roles, list) else [roles]
  804. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  805. data_raw = self.raw_delete(
  806. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  807. data=json.dumps(payload))
  808. return raise_error_from_response(data_raw, KeycloakGetError,
  809. expected_codes=[204])
  810. def get_composite_realm_roles_of_role(self, role_name):
  811. """
  812. Get composite roles of the role
  813. :param role_name: The name of the role
  814. :return Keycloak server response (array RoleRepresentation)
  815. """
  816. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  817. data_raw = self.raw_get(
  818. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  819. return raise_error_from_response(data_raw, KeycloakGetError)
  820. def assign_realm_roles(self, user_id, client_id, roles):
  821. """
  822. Assign realm roles to a user
  823. :param user_id: id of user
  824. :param client_id: id of client containing role (not client-id)
  825. :param roles: roles list or role (use RoleRepresentation)
  826. :return Keycloak server response
  827. """
  828. payload = roles if isinstance(roles, list) else [roles]
  829. params_path = {"realm-name": self.realm_name, "id": user_id}
  830. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  831. data=json.dumps(payload))
  832. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  833. def assign_group_realm_roles(self, group_id, roles):
  834. """
  835. Assign realm roles to a group
  836. :param group_id: id of groupp
  837. :param roles: roles list or role (use GroupRoleRepresentation)
  838. :return Keycloak server response
  839. """
  840. payload = roles if isinstance(roles, list) else [roles]
  841. params_path = {"realm-name": self.realm_name, "id": group_id}
  842. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  843. data=json.dumps(payload))
  844. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  845. def delete_group_realm_roles(self, group_id, roles):
  846. """
  847. Delete realm roles of a group
  848. :param group_id: id of group
  849. :param roles: roles list or role (use GroupRoleRepresentation)
  850. :return Keycloak server response
  851. """
  852. payload = roles if isinstance(roles, list) else [roles]
  853. params_path = {"realm-name": self.realm_name, "id": group_id}
  854. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  855. data=json.dumps(payload))
  856. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  857. def get_group_realm_roles(self, group_id):
  858. """
  859. Get all realm roles for a group.
  860. :param user_id: id of the group
  861. :return: Keycloak server response (array RoleRepresentation)
  862. """
  863. params_path = {"realm-name": self.realm_name, "id": group_id}
  864. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  865. return raise_error_from_response(data_raw, KeycloakGetError)
  866. def assign_group_client_roles(self, group_id, client_id, roles):
  867. """
  868. Assign client roles to a group
  869. :param group_id: id of group
  870. :param client_id: id of client (not client-id)
  871. :param roles: roles list or role (use GroupRoleRepresentation)
  872. :return Keycloak server response
  873. """
  874. payload = roles if isinstance(roles, list) else [roles]
  875. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  876. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  877. data=json.dumps(payload))
  878. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  879. def delete_group_client_roles(self, group_id, client_id, roles):
  880. """
  881. Delete client roles of a group
  882. :param group_id: id of group
  883. :param client_id: id of client (not client-id)
  884. :param roles: roles list or role (use GroupRoleRepresentation)
  885. :return Keycloak server response
  886. """
  887. payload = roles if isinstance(roles, list) else [roles]
  888. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  889. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  890. return raise_error_from_response(data_raw, KeycloakGetError)
  891. def get_group_client_roles(self, group_id, client_id, roles):
  892. """
  893. Get client roles of a group
  894. :param group_id: id of group
  895. :param client_id: id of client (not client-id)
  896. :param roles: roles list or role (use GroupRoleRepresentation)
  897. :return Keycloak server response (array RoleRepresentation)
  898. """
  899. payload = roles if isinstance(roles, list) else [roles]
  900. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  901. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  902. data=json.dumps(payload))
  903. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  904. def get_client_roles_of_user(self, user_id, client_id):
  905. """
  906. Get all client roles for a user.
  907. :param user_id: id of user
  908. :param client_id: id of client (not client-id)
  909. :return: Keycloak server response (array RoleRepresentation)
  910. """
  911. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  912. def get_available_client_roles_of_user(self, user_id, client_id):
  913. """
  914. Get available client role-mappings for a user.
  915. :param user_id: id of user
  916. :param client_id: id of client (not client-id)
  917. :return: Keycloak server response (array RoleRepresentation)
  918. """
  919. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  920. def get_composite_client_roles_of_user(self, user_id, client_id):
  921. """
  922. Get composite client role-mappings for a user.
  923. :param user_id: id of user
  924. :param client_id: id of client (not client-id)
  925. :return: Keycloak server response (array RoleRepresentation)
  926. """
  927. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  928. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  929. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  930. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  931. return raise_error_from_response(data_raw, KeycloakGetError)
  932. def delete_client_roles_of_user(self, user_id, client_id, roles):
  933. """
  934. Delete client roles from a user.
  935. :param user_id: id of user
  936. :param client_id: id of client containing role (not client-id)
  937. :param roles: roles list or role to delete (use RoleRepresentation)
  938. :return: Keycloak server response
  939. """
  940. payload = roles if isinstance(roles, list) else [roles]
  941. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  942. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  943. data=json.dumps(payload))
  944. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  945. def get_authentication_flows(self):
  946. """
  947. Get authentication flows. Returns all flow details
  948. AuthenticationFlowRepresentation
  949. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  950. :return: Keycloak server response (AuthenticationFlowRepresentation)
  951. """
  952. params_path = {"realm-name": self.realm_name}
  953. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  954. return raise_error_from_response(data_raw, KeycloakGetError)
  955. def create_authentication_flow(self, payload, skip_exists=False):
  956. """
  957. Create a new authentication flow
  958. AuthenticationFlowRepresentation
  959. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  960. :param payload: AuthenticationFlowRepresentation
  961. :param skip_exists: If true then do not raise an error if authentication flow already exists
  962. :return: Keycloak server response (RoleRepresentation)
  963. """
  964. params_path = {"realm-name": self.realm_name}
  965. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  966. data=payload)
  967. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  968. def get_authentication_flow_executions(self, flow_alias):
  969. """
  970. Get authentication flow executions. Returns all execution steps
  971. :param flow_alias: the flow alias
  972. :return: Response(json)
  973. """
  974. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  975. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  976. return raise_error_from_response(data_raw, KeycloakGetError)
  977. def update_authentication_flow_executions(self, payload, flow_alias):
  978. """
  979. Update an authentication flow execution
  980. AuthenticationExecutionInfoRepresentation
  981. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  982. :param payload: AuthenticationExecutionInfoRepresentation
  983. :param flow_alias: The flow alias
  984. :return: Keycloak server response
  985. """
  986. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  987. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  988. data=payload)
  989. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  990. def sync_users(self, storage_id, action):
  991. """
  992. Function to trigger user sync from provider
  993. :param storage_id: The id of the user storage provider
  994. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  995. :return:
  996. """
  997. data = {'action': action}
  998. params_query = {"action": action}
  999. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1000. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1001. data=json.dumps(data), **params_query)
  1002. return raise_error_from_response(data_raw, KeycloakGetError)
  1003. def get_client_scopes(self):
  1004. """
  1005. Get representation of the client scopes for the realm where we are connected to
  1006. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1007. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1008. """
  1009. params_path = {"realm-name": self.realm_name}
  1010. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1011. return raise_error_from_response(data_raw, KeycloakGetError)
  1012. def get_client_scope(self, client_scope_id):
  1013. """
  1014. Get representation of the client scopes for the realm where we are connected to
  1015. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1016. :param client_scope_id: The id of the client scope
  1017. :return: Keycloak server response (ClientScopeRepresentation)
  1018. """
  1019. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1020. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1021. return raise_error_from_response(data_raw, KeycloakGetError)
  1022. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1023. """
  1024. Add a mapper to a client scope
  1025. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1026. :param client_scope_id: The id of the client scope
  1027. :param payload: ProtocolMapperRepresentation
  1028. :return: Keycloak server Response
  1029. """
  1030. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1031. data_raw = self.raw_post(
  1032. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1033. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1034. def generate_client_secrets(self, client_id):
  1035. """
  1036. Generate a new secret for the client
  1037. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1038. :param client_id: id of client (not client-id)
  1039. :return: Keycloak server response (ClientRepresentation)
  1040. """
  1041. params_path = {"realm-name": self.realm_name, "id": client_id}
  1042. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1043. return raise_error_from_response(data_raw, KeycloakGetError)
  1044. def get_client_secrets(self, client_id):
  1045. """
  1046. Get representation of the client secrets
  1047. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1048. :param client_id: id of client (not client-id)
  1049. :return: Keycloak server response (ClientRepresentation)
  1050. """
  1051. params_path = {"realm-name": self.realm_name, "id": client_id}
  1052. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1053. return raise_error_from_response(data_raw, KeycloakGetError)
  1054. def get_components(self, query=None):
  1055. """
  1056. Return a list of components, filtered according to query parameters
  1057. ComponentRepresentation
  1058. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1059. :param query: Query parameters (optional)
  1060. :return: components list
  1061. """
  1062. params_path = {"realm-name": self.realm_name}
  1063. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1064. data=None, **query)
  1065. return raise_error_from_response(data_raw, KeycloakGetError)
  1066. def create_component(self, payload):
  1067. """
  1068. Create a new component.
  1069. ComponentRepresentation
  1070. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1071. :param payload: ComponentRepresentation
  1072. :return: UserRepresentation
  1073. """
  1074. params_path = {"realm-name": self.realm_name}
  1075. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1076. data=json.dumps(payload))
  1077. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1078. def get_component(self, component_id):
  1079. """
  1080. Get representation of the component
  1081. :param component_id: Component id
  1082. ComponentRepresentation
  1083. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1084. :return: ComponentRepresentation
  1085. """
  1086. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1087. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1088. return raise_error_from_response(data_raw, KeycloakGetError)
  1089. def update_component(self, component_id, payload):
  1090. """
  1091. Update the component
  1092. :param component_id: Component id
  1093. :param payload: ComponentRepresentation
  1094. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1095. :return: Http response
  1096. """
  1097. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1098. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1099. data=json.dumps(payload))
  1100. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1101. def delete_component(self, component_id):
  1102. """
  1103. Delete the component
  1104. :param component_id: Component id
  1105. :return: Http response
  1106. """
  1107. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1108. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1109. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1110. def get_keys(self):
  1111. """
  1112. Return a list of keys, filtered according to query parameters
  1113. KeysMetadataRepresentation
  1114. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1115. :return: keys list
  1116. """
  1117. params_path = {"realm-name": self.realm_name}
  1118. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1119. data=None)
  1120. return raise_error_from_response(data_raw, KeycloakGetError)
  1121. def raw_get(self, *args, **kwargs):
  1122. """
  1123. Calls connection.raw_get.
  1124. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1125. and try *get* once more.
  1126. """
  1127. r = self.connection.raw_get(*args, **kwargs)
  1128. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1129. self.refresh_token()
  1130. return self.connection.raw_get(*args, **kwargs)
  1131. return r
  1132. def raw_post(self, *args, **kwargs):
  1133. """
  1134. Calls connection.raw_post.
  1135. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1136. and try *post* once more.
  1137. """
  1138. r = self.connection.raw_post(*args, **kwargs)
  1139. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1140. self.refresh_token()
  1141. return self.connection.raw_post(*args, **kwargs)
  1142. return r
  1143. def raw_put(self, *args, **kwargs):
  1144. """
  1145. Calls connection.raw_put.
  1146. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1147. and try *put* once more.
  1148. """
  1149. r = self.connection.raw_put(*args, **kwargs)
  1150. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1151. self.refresh_token()
  1152. return self.connection.raw_put(*args, **kwargs)
  1153. return r
  1154. def raw_delete(self, *args, **kwargs):
  1155. """
  1156. Calls connection.raw_delete.
  1157. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1158. and try *delete* once more.
  1159. """
  1160. r = self.connection.raw_delete(*args, **kwargs)
  1161. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1162. self.refresh_token()
  1163. return self.connection.raw_delete(*args, **kwargs)
  1164. return r
  1165. def get_token(self):
  1166. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1167. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1168. client_secret_key=self.client_secret_key,
  1169. custom_headers=self.custom_headers)
  1170. grant_type = ["password"]
  1171. if self.client_secret_key:
  1172. grant_type = ["client_credentials"]
  1173. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1174. headers = {
  1175. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1176. 'Content-Type': 'application/json'
  1177. }
  1178. if self.custom_headers is not None:
  1179. # merge custom headers to main headers
  1180. headers.update(self.custom_headers)
  1181. self._connection = ConnectionManager(base_url=self.server_url,
  1182. headers=headers,
  1183. timeout=60,
  1184. verify=self.verify)
  1185. def refresh_token(self):
  1186. refresh_token = self.token.get('refresh_token')
  1187. try:
  1188. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1189. except KeycloakGetError as e:
  1190. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1191. b'Token is not active' in e.response_body):
  1192. self.get_token()
  1193. else:
  1194. raise
  1195. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))