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.

1499 lines
58 KiB

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