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.

1494 lines
57 KiB

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