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.

1541 lines
59 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. from .connection import ConnectionManager
  31. from .exceptions import raise_error_from_response, KeycloakGetError
  32. from .keycloak_openid import KeycloakOpenID
  33. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  34. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, \
  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, \
  40. 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, \
  44. URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION, URL_ADMIN_FLOWS_EXECUTIONS_FLOW, URL_ADMIN_FLOWS_COPY, \
  45. URL_ADMIN_FLOWS_ALIAS
  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 assign_realm_roles(self, user_id, client_id, roles):
  783. """
  784. Assign realm roles to a user
  785. :param user_id: id of user
  786. :param client_id: id of client containing role (not client-id)
  787. :param roles: roles list or role (use RoleRepresentation)
  788. :return Keycloak server response
  789. """
  790. payload = roles if isinstance(roles, list) else [roles]
  791. params_path = {"realm-name": self.realm_name, "id": user_id}
  792. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  793. data=json.dumps(payload))
  794. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  795. def assign_group_realm_roles(self, group_id, roles):
  796. """
  797. Assign realm roles to a group
  798. :param group_id: id of groupp
  799. :param roles: roles list or role (use GroupRoleRepresentation)
  800. :return Keycloak server response
  801. """
  802. payload = roles if isinstance(roles, list) else [roles]
  803. params_path = {"realm-name": self.realm_name, "id": group_id}
  804. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  805. data=json.dumps(payload))
  806. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  807. def delete_group_realm_roles(self, group_id, roles):
  808. """
  809. Delete realm roles of a group
  810. :param group_id: id of group
  811. :param roles: roles list or role (use GroupRoleRepresentation)
  812. :return Keycloak server response
  813. """
  814. payload = roles if isinstance(roles, list) else [roles]
  815. params_path = {"realm-name": self.realm_name, "id": group_id}
  816. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  817. data=json.dumps(payload))
  818. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  819. def get_group_realm_roles(self, group_id):
  820. """
  821. Get all realm roles for a group.
  822. :param user_id: id of the group
  823. :return: Keycloak server response (array RoleRepresentation)
  824. """
  825. params_path = {"realm-name": self.realm_name, "id": group_id}
  826. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  827. return raise_error_from_response(data_raw, KeycloakGetError)
  828. def assign_group_client_roles(self, group_id, client_id, roles):
  829. """
  830. Assign client roles to a group
  831. :param group_id: id of group
  832. :param client_id: id of client (not client-id)
  833. :param roles: roles list or role (use GroupRoleRepresentation)
  834. :return Keycloak server response
  835. """
  836. payload = roles if isinstance(roles, list) else [roles]
  837. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  838. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  839. data=json.dumps(payload))
  840. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  841. def delete_group_client_roles(self, group_id, client_id, roles):
  842. """
  843. Delete client roles of a group
  844. :param group_id: id of group
  845. :param client_id: id of client (not client-id)
  846. :param roles: roles list or role (use GroupRoleRepresentation)
  847. :return Keycloak server response
  848. """
  849. payload = roles if isinstance(roles, list) else [roles]
  850. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  851. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  852. return raise_error_from_response(data_raw, KeycloakGetError)
  853. def get_group_client_roles(self, group_id, client_id, roles):
  854. """
  855. Get client roles of a group
  856. :param group_id: id of group
  857. :param client_id: id of client (not client-id)
  858. :param roles: roles list or role (use GroupRoleRepresentation)
  859. :return Keycloak server response (array RoleRepresentation)
  860. """
  861. payload = roles if isinstance(roles, list) else [roles]
  862. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  863. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  864. data=json.dumps(payload))
  865. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  866. def get_client_roles_of_user(self, user_id, client_id):
  867. """
  868. Get all client roles for a user.
  869. :param user_id: id of user
  870. :param client_id: id of client (not client-id)
  871. :return: Keycloak server response (array RoleRepresentation)
  872. """
  873. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  874. def get_available_client_roles_of_user(self, user_id, client_id):
  875. """
  876. Get available client role-mappings for a user.
  877. :param user_id: id of user
  878. :param client_id: id of client (not client-id)
  879. :return: Keycloak server response (array RoleRepresentation)
  880. """
  881. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  882. def get_composite_client_roles_of_user(self, user_id, client_id):
  883. """
  884. Get composite client role-mappings for a user.
  885. :param user_id: id of user
  886. :param client_id: id of client (not client-id)
  887. :return: Keycloak server response (array RoleRepresentation)
  888. """
  889. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  890. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  891. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  892. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  893. return raise_error_from_response(data_raw, KeycloakGetError)
  894. def delete_client_roles_of_user(self, user_id, client_id, roles):
  895. """
  896. Delete client roles from a user.
  897. :param user_id: id of user
  898. :param client_id: id of client containing role (not client-id)
  899. :param roles: roles list or role to delete (use RoleRepresentation)
  900. :return: Keycloak server response
  901. """
  902. payload = roles if isinstance(roles, list) else [roles]
  903. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  904. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  905. data=json.dumps(payload))
  906. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  907. def get_authentication_flows(self):
  908. """
  909. Get authentication flows. Returns all flow details
  910. AuthenticationFlowRepresentation
  911. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  912. :return: Keycloak server response (AuthenticationFlowRepresentation)
  913. """
  914. params_path = {"realm-name": self.realm_name}
  915. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  916. return raise_error_from_response(data_raw, KeycloakGetError)
  917. def get_authentication_flow_for_id(self, flow_id):
  918. """
  919. Get one authentication flow by it's id/alias. Returns all flow details
  920. AuthenticationFlowRepresentation
  921. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  922. :param flow_id: the id of a flow NOT it's alias
  923. :return: Keycloak server response (AuthenticationFlowRepresentation)
  924. """
  925. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  926. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  927. return raise_error_from_response(data_raw, KeycloakGetError)
  928. def create_authentication_flow(self, payload, skip_exists=False):
  929. """
  930. Create a new authentication flow
  931. AuthenticationFlowRepresentation
  932. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  933. :param payload: AuthenticationFlowRepresentation
  934. :param skip_exists: If true then do not raise an error if authentication flow already exists
  935. :return: Keycloak server response (RoleRepresentation)
  936. """
  937. params_path = {"realm-name": self.realm_name}
  938. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  939. data=payload)
  940. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  941. def copy_authentication_flow(self, payload, flow_alias):
  942. """
  943. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  944. :param payload: JSON containing 'newName' attribute
  945. :param flow_alias: the flow alias
  946. :return: Keycloak server response (RoleRepresentation)
  947. """
  948. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  949. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  950. data=payload)
  951. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  952. def get_authentication_flow_executions(self, flow_alias):
  953. """
  954. Get authentication flow executions. Returns all execution steps
  955. :param flow_alias: the flow alias
  956. :return: Response(json)
  957. """
  958. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  959. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  960. return raise_error_from_response(data_raw, KeycloakGetError)
  961. def update_authentication_flow_executions(self, payload, flow_alias):
  962. """
  963. Update an authentication flow execution
  964. AuthenticationExecutionInfoRepresentation
  965. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  966. :param payload: AuthenticationExecutionInfoRepresentation
  967. :param flow_alias: The flow alias
  968. :return: Keycloak server response
  969. """
  970. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  971. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  972. data=payload)
  973. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  974. def create_authentication_flow_execution(self, payload, flow_alias):
  975. """
  976. Create an authentication flow execution
  977. AuthenticationExecutionInfoRepresentation
  978. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  979. :param payload: AuthenticationExecutionInfoRepresentation
  980. :param flow_alias: The flow alias
  981. :return: Keycloak server response
  982. """
  983. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  984. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  985. data=payload)
  986. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  987. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  988. """
  989. Create a new sub authentication flow for a given authentication flow
  990. AuthenticationFlowRepresentation
  991. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  992. :param payload: AuthenticationFlowRepresentation
  993. :param flow_alias: The flow alias
  994. :param skip_exists: If true then do not raise an error if authentication flow already exists
  995. :return: Keycloak server response (RoleRepresentation)
  996. """
  997. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  998. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  999. data=payload)
  1000. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1001. def sync_users(self, storage_id, action):
  1002. """
  1003. Function to trigger user sync from provider
  1004. :param storage_id: The id of the user storage provider
  1005. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1006. :return:
  1007. """
  1008. data = {'action': action}
  1009. params_query = {"action": action}
  1010. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1011. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1012. data=json.dumps(data), **params_query)
  1013. return raise_error_from_response(data_raw, KeycloakGetError)
  1014. def get_client_scopes(self):
  1015. """
  1016. Get representation of the client scopes for the realm where we are connected to
  1017. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1018. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1019. """
  1020. params_path = {"realm-name": self.realm_name}
  1021. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1022. return raise_error_from_response(data_raw, KeycloakGetError)
  1023. def get_client_scope(self, client_scope_id):
  1024. """
  1025. Get representation of the client scopes for the realm where we are connected to
  1026. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1027. :param client_scope_id: The id of the client scope
  1028. :return: Keycloak server response (ClientScopeRepresentation)
  1029. """
  1030. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1031. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1032. return raise_error_from_response(data_raw, KeycloakGetError)
  1033. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1034. """
  1035. Add a mapper to a client scope
  1036. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1037. :param client_scope_id: The id of the client scope
  1038. :param payload: ProtocolMapperRepresentation
  1039. :return: Keycloak server Response
  1040. """
  1041. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1042. data_raw = self.raw_post(
  1043. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1044. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1045. def generate_client_secrets(self, client_id):
  1046. """
  1047. Generate a new secret for the client
  1048. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1049. :param client_id: id of client (not client-id)
  1050. :return: Keycloak server response (ClientRepresentation)
  1051. """
  1052. params_path = {"realm-name": self.realm_name, "id": client_id}
  1053. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1054. return raise_error_from_response(data_raw, KeycloakGetError)
  1055. def get_client_secrets(self, client_id):
  1056. """
  1057. Get representation of the client secrets
  1058. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1059. :param client_id: id of client (not client-id)
  1060. :return: Keycloak server response (ClientRepresentation)
  1061. """
  1062. params_path = {"realm-name": self.realm_name, "id": client_id}
  1063. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1064. return raise_error_from_response(data_raw, KeycloakGetError)
  1065. def get_components(self, query=None):
  1066. """
  1067. Return a list of components, filtered according to query parameters
  1068. ComponentRepresentation
  1069. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1070. :param query: Query parameters (optional)
  1071. :return: components list
  1072. """
  1073. params_path = {"realm-name": self.realm_name}
  1074. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1075. data=None, **query)
  1076. return raise_error_from_response(data_raw, KeycloakGetError)
  1077. def create_component(self, payload):
  1078. """
  1079. Create a new component.
  1080. ComponentRepresentation
  1081. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1082. :param payload: ComponentRepresentation
  1083. :return: UserRepresentation
  1084. """
  1085. params_path = {"realm-name": self.realm_name}
  1086. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1087. data=json.dumps(payload))
  1088. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1089. def get_component(self, component_id):
  1090. """
  1091. Get representation of the component
  1092. :param component_id: Component id
  1093. ComponentRepresentation
  1094. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1095. :return: ComponentRepresentation
  1096. """
  1097. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1098. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1099. return raise_error_from_response(data_raw, KeycloakGetError)
  1100. def update_component(self, component_id, payload):
  1101. """
  1102. Update the component
  1103. :param component_id: Component id
  1104. :param payload: ComponentRepresentation
  1105. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1106. :return: Http response
  1107. """
  1108. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1109. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1110. data=json.dumps(payload))
  1111. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1112. def delete_component(self, component_id):
  1113. """
  1114. Delete the component
  1115. :param component_id: Component id
  1116. :return: Http response
  1117. """
  1118. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1119. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1120. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1121. def get_keys(self):
  1122. """
  1123. Return a list of keys, filtered according to query parameters
  1124. KeysMetadataRepresentation
  1125. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1126. :return: keys list
  1127. """
  1128. params_path = {"realm-name": self.realm_name}
  1129. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1130. data=None)
  1131. return raise_error_from_response(data_raw, KeycloakGetError)
  1132. def raw_get(self, *args, **kwargs):
  1133. """
  1134. Calls connection.raw_get.
  1135. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1136. and try *get* once more.
  1137. """
  1138. r = self.connection.raw_get(*args, **kwargs)
  1139. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1140. self.refresh_token()
  1141. return self.connection.raw_get(*args, **kwargs)
  1142. return r
  1143. def raw_post(self, *args, **kwargs):
  1144. """
  1145. Calls connection.raw_post.
  1146. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1147. and try *post* once more.
  1148. """
  1149. r = self.connection.raw_post(*args, **kwargs)
  1150. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1151. self.refresh_token()
  1152. return self.connection.raw_post(*args, **kwargs)
  1153. return r
  1154. def raw_put(self, *args, **kwargs):
  1155. """
  1156. Calls connection.raw_put.
  1157. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1158. and try *put* once more.
  1159. """
  1160. r = self.connection.raw_put(*args, **kwargs)
  1161. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1162. self.refresh_token()
  1163. return self.connection.raw_put(*args, **kwargs)
  1164. return r
  1165. def raw_delete(self, *args, **kwargs):
  1166. """
  1167. Calls connection.raw_delete.
  1168. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1169. and try *delete* once more.
  1170. """
  1171. r = self.connection.raw_delete(*args, **kwargs)
  1172. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1173. self.refresh_token()
  1174. return self.connection.raw_delete(*args, **kwargs)
  1175. return r
  1176. def get_token(self):
  1177. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1178. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1179. client_secret_key=self.client_secret_key,
  1180. custom_headers=self.custom_headers)
  1181. grant_type = ["password"]
  1182. if self.client_secret_key:
  1183. grant_type = ["client_credentials"]
  1184. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1185. headers = {
  1186. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1187. 'Content-Type': 'application/json'
  1188. }
  1189. if self.custom_headers is not None:
  1190. # merge custom headers to main headers
  1191. headers.update(self.custom_headers)
  1192. self._connection = ConnectionManager(base_url=self.server_url,
  1193. headers=headers,
  1194. timeout=60,
  1195. verify=self.verify)
  1196. def refresh_token(self):
  1197. refresh_token = self.token.get('refresh_token')
  1198. try:
  1199. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1200. except KeycloakGetError as e:
  1201. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1202. b'Token is not active' in e.response_body):
  1203. self.get_token()
  1204. else:
  1205. raise
  1206. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))