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.

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