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.

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