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.

1638 lines
63 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. 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 assign_group_realm_roles(self, group_id, roles):
  848. """
  849. Assign realm roles to a group
  850. :param group_id: id of groupp
  851. :param roles: roles list or role (use GroupRoleRepresentation)
  852. :return Keycloak server response
  853. """
  854. payload = roles if isinstance(roles, list) else [roles]
  855. params_path = {"realm-name": self.realm_name, "id": group_id}
  856. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  857. data=json.dumps(payload))
  858. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  859. def delete_group_realm_roles(self, group_id, roles):
  860. """
  861. Delete realm roles of a group
  862. :param group_id: id of group
  863. :param roles: roles list or role (use GroupRoleRepresentation)
  864. :return Keycloak server response
  865. """
  866. payload = roles if isinstance(roles, list) else [roles]
  867. params_path = {"realm-name": self.realm_name, "id": group_id}
  868. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  869. data=json.dumps(payload))
  870. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  871. def get_group_realm_roles(self, group_id):
  872. """
  873. Get all realm roles for a group.
  874. :param user_id: id of the group
  875. :return: Keycloak server response (array RoleRepresentation)
  876. """
  877. params_path = {"realm-name": self.realm_name, "id": group_id}
  878. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  879. return raise_error_from_response(data_raw, KeycloakGetError)
  880. def assign_group_client_roles(self, group_id, client_id, roles):
  881. """
  882. Assign client roles to a group
  883. :param group_id: id of group
  884. :param client_id: id of client (not client-id)
  885. :param roles: roles list or role (use GroupRoleRepresentation)
  886. :return Keycloak server response
  887. """
  888. payload = roles if isinstance(roles, list) else [roles]
  889. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  890. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  891. data=json.dumps(payload))
  892. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  893. def get_group_client_roles(self, group_id, client_id):
  894. """
  895. Get client roles of a group
  896. :param group_id: id of group
  897. :param client_id: id of client (not client-id)
  898. :return Keycloak server response
  899. """
  900. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  901. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  902. return raise_error_from_response(data_raw, KeycloakGetError)
  903. def delete_group_client_roles(self, group_id, client_id, roles):
  904. """
  905. Delete client roles of a group
  906. :param group_id: id of group
  907. :param client_id: id of client (not client-id)
  908. :param roles: roles list or role (use GroupRoleRepresentation)
  909. :return Keycloak server response (array RoleRepresentation)
  910. """
  911. payload = roles if isinstance(roles, list) else [roles]
  912. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  913. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  914. data=json.dumps(payload))
  915. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  916. def get_client_roles_of_user(self, user_id, client_id):
  917. """
  918. Get all client roles for a user.
  919. :param user_id: id of user
  920. :param client_id: id of client (not client-id)
  921. :return: Keycloak server response (array RoleRepresentation)
  922. """
  923. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  924. def get_available_client_roles_of_user(self, user_id, client_id):
  925. """
  926. Get available client role-mappings for a user.
  927. :param user_id: id of user
  928. :param client_id: id of client (not client-id)
  929. :return: Keycloak server response (array RoleRepresentation)
  930. """
  931. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  932. def get_composite_client_roles_of_user(self, user_id, client_id):
  933. """
  934. Get composite client role-mappings for a user.
  935. :param user_id: id of user
  936. :param client_id: id of client (not client-id)
  937. :return: Keycloak server response (array RoleRepresentation)
  938. """
  939. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  940. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  941. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  942. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  943. return raise_error_from_response(data_raw, KeycloakGetError)
  944. def delete_client_roles_of_user(self, user_id, client_id, roles):
  945. """
  946. Delete client roles from a user.
  947. :param user_id: id of user
  948. :param client_id: id of client containing role (not client-id)
  949. :param roles: roles list or role to delete (use RoleRepresentation)
  950. :return: Keycloak server response
  951. """
  952. payload = roles if isinstance(roles, list) else [roles]
  953. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  954. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  955. data=json.dumps(payload))
  956. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  957. def get_authentication_flows(self):
  958. """
  959. Get authentication flows. Returns all flow details
  960. AuthenticationFlowRepresentation
  961. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  962. :return: Keycloak server response (AuthenticationFlowRepresentation)
  963. """
  964. params_path = {"realm-name": self.realm_name}
  965. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  966. return raise_error_from_response(data_raw, KeycloakGetError)
  967. def get_authentication_flow_for_id(self, flow_id):
  968. """
  969. Get one authentication flow by it's id/alias. Returns all flow details
  970. AuthenticationFlowRepresentation
  971. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  972. :param flow_id: the id of a flow NOT it's alias
  973. :return: Keycloak server response (AuthenticationFlowRepresentation)
  974. """
  975. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  976. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  977. return raise_error_from_response(data_raw, KeycloakGetError)
  978. def create_authentication_flow(self, payload, skip_exists=False):
  979. """
  980. Create a new authentication flow
  981. AuthenticationFlowRepresentation
  982. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  983. :param payload: AuthenticationFlowRepresentation
  984. :param skip_exists: If true then do not raise an error if authentication flow already exists
  985. :return: Keycloak server response (RoleRepresentation)
  986. """
  987. params_path = {"realm-name": self.realm_name}
  988. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  989. data=payload)
  990. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  991. def copy_authentication_flow(self, payload, flow_alias):
  992. """
  993. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  994. :param payload: JSON containing 'newName' attribute
  995. :param flow_alias: the flow alias
  996. :return: Keycloak server response (RoleRepresentation)
  997. """
  998. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  999. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1000. data=payload)
  1001. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1002. def get_authentication_flow_executions(self, flow_alias):
  1003. """
  1004. Get authentication flow executions. Returns all execution steps
  1005. :param flow_alias: the flow alias
  1006. :return: Response(json)
  1007. """
  1008. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1009. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1010. return raise_error_from_response(data_raw, KeycloakGetError)
  1011. def update_authentication_flow_executions(self, payload, flow_alias):
  1012. """
  1013. Update an authentication flow execution
  1014. AuthenticationExecutionInfoRepresentation
  1015. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1016. :param payload: AuthenticationExecutionInfoRepresentation
  1017. :param flow_alias: The flow alias
  1018. :return: Keycloak server response
  1019. """
  1020. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1021. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1022. data=payload)
  1023. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1024. def create_authentication_flow_execution(self, payload, flow_alias):
  1025. """
  1026. Create an authentication flow execution
  1027. AuthenticationExecutionInfoRepresentation
  1028. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1029. :param payload: AuthenticationExecutionInfoRepresentation
  1030. :param flow_alias: The flow alias
  1031. :return: Keycloak server response
  1032. """
  1033. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1034. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1035. data=payload)
  1036. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1037. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1038. """
  1039. Create a new sub authentication flow for a given authentication flow
  1040. AuthenticationFlowRepresentation
  1041. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1042. :param payload: AuthenticationFlowRepresentation
  1043. :param flow_alias: The flow alias
  1044. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1045. :return: Keycloak server response (RoleRepresentation)
  1046. """
  1047. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1048. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1049. data=payload)
  1050. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1051. def sync_users(self, storage_id, action):
  1052. """
  1053. Function to trigger user sync from provider
  1054. :param storage_id: The id of the user storage provider
  1055. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1056. :return:
  1057. """
  1058. data = {'action': action}
  1059. params_query = {"action": action}
  1060. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1061. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1062. data=json.dumps(data), **params_query)
  1063. return raise_error_from_response(data_raw, KeycloakGetError)
  1064. def get_client_scopes(self):
  1065. """
  1066. Get representation of the client scopes for the realm where we are connected to
  1067. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1068. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1069. """
  1070. params_path = {"realm-name": self.realm_name}
  1071. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1072. return raise_error_from_response(data_raw, KeycloakGetError)
  1073. def get_client_scope(self, client_scope_id):
  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. :param client_scope_id: The id of the client scope
  1078. :return: Keycloak server response (ClientScopeRepresentation)
  1079. """
  1080. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1081. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1082. return raise_error_from_response(data_raw, KeycloakGetError)
  1083. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1084. """
  1085. Add a mapper to a client scope
  1086. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1087. :param client_scope_id: The id of the client scope
  1088. :param payload: ProtocolMapperRepresentation
  1089. :return: Keycloak server Response
  1090. """
  1091. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1092. data_raw = self.raw_post(
  1093. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1094. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1095. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1096. """
  1097. Delete a mapper from a client scope
  1098. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1099. :param client_scope_id: The id of the client scope
  1100. :param payload: ProtocolMapperRepresentation
  1101. :return: Keycloak server Response
  1102. """
  1103. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1104. "protocol-mapper-id": protocol_mppaer_id}
  1105. data_raw = self.raw_delete(
  1106. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1107. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1108. def add_mapper_to_client(self, client_id, payload):
  1109. """
  1110. Add a mapper to a client
  1111. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1112. :param client_id: The id of the client
  1113. :param payload: ProtocolMapperRepresentation
  1114. :return: Keycloak server Response
  1115. """
  1116. params_path = {"realm-name": self.realm_name, "id": client_id}
  1117. data_raw = self.raw_post(
  1118. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1119. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1120. def generate_client_secrets(self, client_id):
  1121. """
  1122. Generate a new secret for the client
  1123. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1124. :param client_id: id of client (not client-id)
  1125. :return: Keycloak server response (ClientRepresentation)
  1126. """
  1127. params_path = {"realm-name": self.realm_name, "id": client_id}
  1128. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1129. return raise_error_from_response(data_raw, KeycloakGetError)
  1130. def get_client_secrets(self, client_id):
  1131. """
  1132. Get representation of the client secrets
  1133. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1134. :param client_id: id of client (not client-id)
  1135. :return: Keycloak server response (ClientRepresentation)
  1136. """
  1137. params_path = {"realm-name": self.realm_name, "id": client_id}
  1138. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1139. return raise_error_from_response(data_raw, KeycloakGetError)
  1140. def get_components(self, query=None):
  1141. """
  1142. Return a list of components, filtered according to query parameters
  1143. ComponentRepresentation
  1144. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1145. :param query: Query parameters (optional)
  1146. :return: components list
  1147. """
  1148. params_path = {"realm-name": self.realm_name}
  1149. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1150. data=None, **query)
  1151. return raise_error_from_response(data_raw, KeycloakGetError)
  1152. def create_component(self, payload):
  1153. """
  1154. Create a new component.
  1155. ComponentRepresentation
  1156. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1157. :param payload: ComponentRepresentation
  1158. :return: UserRepresentation
  1159. """
  1160. params_path = {"realm-name": self.realm_name}
  1161. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1162. data=json.dumps(payload))
  1163. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1164. def get_component(self, component_id):
  1165. """
  1166. Get representation of the component
  1167. :param component_id: Component id
  1168. ComponentRepresentation
  1169. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1170. :return: ComponentRepresentation
  1171. """
  1172. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1173. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1174. return raise_error_from_response(data_raw, KeycloakGetError)
  1175. def update_component(self, component_id, payload):
  1176. """
  1177. Update the component
  1178. :param component_id: Component id
  1179. :param payload: ComponentRepresentation
  1180. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1181. :return: Http response
  1182. """
  1183. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1184. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1185. data=json.dumps(payload))
  1186. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1187. def delete_component(self, component_id):
  1188. """
  1189. Delete the component
  1190. :param component_id: Component id
  1191. :return: Http response
  1192. """
  1193. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1194. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1195. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1196. def get_keys(self):
  1197. """
  1198. Return a list of keys, filtered according to query parameters
  1199. KeysMetadataRepresentation
  1200. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1201. :return: keys list
  1202. """
  1203. params_path = {"realm-name": self.realm_name}
  1204. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1205. data=None)
  1206. return raise_error_from_response(data_raw, KeycloakGetError)
  1207. def raw_get(self, *args, **kwargs):
  1208. """
  1209. Calls connection.raw_get.
  1210. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1211. and try *get* once more.
  1212. """
  1213. r = self.connection.raw_get(*args, **kwargs)
  1214. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1215. self.refresh_token()
  1216. return self.connection.raw_get(*args, **kwargs)
  1217. return r
  1218. def raw_post(self, *args, **kwargs):
  1219. """
  1220. Calls connection.raw_post.
  1221. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1222. and try *post* once more.
  1223. """
  1224. r = self.connection.raw_post(*args, **kwargs)
  1225. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1226. self.refresh_token()
  1227. return self.connection.raw_post(*args, **kwargs)
  1228. return r
  1229. def raw_put(self, *args, **kwargs):
  1230. """
  1231. Calls connection.raw_put.
  1232. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1233. and try *put* once more.
  1234. """
  1235. r = self.connection.raw_put(*args, **kwargs)
  1236. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1237. self.refresh_token()
  1238. return self.connection.raw_put(*args, **kwargs)
  1239. return r
  1240. def raw_delete(self, *args, **kwargs):
  1241. """
  1242. Calls connection.raw_delete.
  1243. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1244. and try *delete* once more.
  1245. """
  1246. r = self.connection.raw_delete(*args, **kwargs)
  1247. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1248. self.refresh_token()
  1249. return self.connection.raw_delete(*args, **kwargs)
  1250. return r
  1251. def get_token(self):
  1252. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1253. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1254. client_secret_key=self.client_secret_key,
  1255. custom_headers=self.custom_headers)
  1256. grant_type = ["password"]
  1257. if self.client_secret_key:
  1258. grant_type = ["client_credentials"]
  1259. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1260. headers = {
  1261. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1262. 'Content-Type': 'application/json'
  1263. }
  1264. if self.custom_headers is not None:
  1265. # merge custom headers to main headers
  1266. headers.update(self.custom_headers)
  1267. self._connection = ConnectionManager(base_url=self.server_url,
  1268. headers=headers,
  1269. timeout=60,
  1270. verify=self.verify)
  1271. def refresh_token(self):
  1272. refresh_token = self.token.get('refresh_token')
  1273. try:
  1274. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1275. except KeycloakGetError as e:
  1276. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1277. b'Token is not active' in e.response_body):
  1278. self.get_token()
  1279. else:
  1280. raise
  1281. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))