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.

1512 lines
58 KiB

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