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.

1505 lines
58 KiB

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