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.

1650 lines
64 KiB

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