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.

2003 lines
80 KiB

8 years ago
7 years ago
6 years ago
4 years ago
6 years ago
8 years ago
6 years ago
4 years ago
4 years ago
5 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
4 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
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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 Iterable
  28. from .connection import ConnectionManager
  29. from .exceptions import raise_error_from_response, KeycloakGetError
  30. from .keycloak_openid import KeycloakOpenID
  31. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  32. URL_ADMIN_CLIENT_AUTHZ_POLICIES, URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_POLICY, URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_PERMISSION, \
  33. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_GROUPS_REALM_ROLES, \
  34. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE, URL_ADMIN_CLIENT_INSTALLATION_PROVIDER, \
  35. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GROUPS_CLIENT_ROLES, \
  36. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  37. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  38. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  39. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  40. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, URL_ADMIN_IDP, \
  41. URL_ADMIN_IDP_MAPPERS, URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  42. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  43. URL_ADMIN_USER_REALM_ROLES, URL_ADMIN_REALM, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS, \
  44. URL_ADMIN_USER_FEDERATED_IDENTITY, URL_ADMIN_USER_FEDERATED_IDENTITIES, URL_ADMIN_CLIENT_ROLE_MEMBERS, \
  45. URL_ADMIN_REALM_ROLES_MEMBERS, URL_ADMIN_CLIENT_PROTOCOL_MAPPER, URL_ADMIN_CLIENT_SCOPES_MAPPERS, \
  46. URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION, URL_ADMIN_FLOWS_EXECUTIONS_FLOW, URL_ADMIN_FLOWS_COPY, \
  47. URL_ADMIN_FLOWS_ALIAS, URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER, URL_ADMIN_AUTHENTICATOR_CONFIG, \
  48. URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE, URL_ADMIN_CLIENT_ALL_SESSIONS, URL_ADMIN_EVENTS, \
  49. URL_ADMIN_REALM_EXPORT, URL_ADMIN_DELETE_USER_ROLE, URL_ADMIN_USER_LOGOUT
  50. class KeycloakAdmin:
  51. PAGE_SIZE = 100
  52. _server_url = None
  53. _username = None
  54. _password = None
  55. _realm_name = None
  56. _client_id = None
  57. _verify = None
  58. _client_secret_key = None
  59. _auto_refresh_token = None
  60. _connection = None
  61. _token = None
  62. _custom_headers = None
  63. _user_realm_name = None
  64. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  65. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  66. """
  67. :param server_url: Keycloak server url
  68. :param username: admin username
  69. :param password: admin password
  70. :param realm_name: realm name
  71. :param client_id: client id
  72. :param verify: True if want check connection SSL
  73. :param client_secret_key: client secret key (optional, required only for access type confidential)
  74. :param custom_headers: dict of custom header to pass to each HTML request
  75. :param user_realm_name: The realm name of the user, if different from realm_name
  76. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  77. """
  78. self.server_url = server_url
  79. self.username = username
  80. self.password = password
  81. self.realm_name = realm_name
  82. self.client_id = client_id
  83. self.verify = verify
  84. self.client_secret_key = client_secret_key
  85. self.auto_refresh_token = auto_refresh_token or []
  86. self.user_realm_name = user_realm_name
  87. self.custom_headers = custom_headers
  88. # Get token Admin
  89. self.get_token()
  90. @property
  91. def server_url(self):
  92. return self._server_url
  93. @server_url.setter
  94. def server_url(self, value):
  95. self._server_url = value
  96. @property
  97. def realm_name(self):
  98. return self._realm_name
  99. @realm_name.setter
  100. def realm_name(self, value):
  101. self._realm_name = value
  102. @property
  103. def connection(self):
  104. return self._connection
  105. @connection.setter
  106. def connection(self, value):
  107. self._connection = value
  108. @property
  109. def client_id(self):
  110. return self._client_id
  111. @client_id.setter
  112. def client_id(self, value):
  113. self._client_id = value
  114. @property
  115. def client_secret_key(self):
  116. return self._client_secret_key
  117. @client_secret_key.setter
  118. def client_secret_key(self, value):
  119. self._client_secret_key = value
  120. @property
  121. def verify(self):
  122. return self._verify
  123. @verify.setter
  124. def verify(self, value):
  125. self._verify = value
  126. @property
  127. def username(self):
  128. return self._username
  129. @username.setter
  130. def username(self, value):
  131. self._username = value
  132. @property
  133. def password(self):
  134. return self._password
  135. @password.setter
  136. def password(self, value):
  137. self._password = value
  138. @property
  139. def token(self):
  140. return self._token
  141. @token.setter
  142. def token(self, value):
  143. self._token = value
  144. @property
  145. def auto_refresh_token(self):
  146. return self._auto_refresh_token
  147. @property
  148. def user_realm_name(self):
  149. return self._user_realm_name
  150. @user_realm_name.setter
  151. def user_realm_name(self, value):
  152. self._user_realm_name = value
  153. @property
  154. def custom_headers(self):
  155. return self._custom_headers
  156. @custom_headers.setter
  157. def custom_headers(self, value):
  158. self._custom_headers = value
  159. @auto_refresh_token.setter
  160. def auto_refresh_token(self, value):
  161. allowed_methods = {'get', 'post', 'put', 'delete'}
  162. if not isinstance(value, Iterable):
  163. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  164. if not all(method in allowed_methods for method in value):
  165. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  166. self._auto_refresh_token = value
  167. def __fetch_all(self, url, query=None):
  168. '''Wrapper function to paginate GET requests
  169. :param url: The url on which the query is executed
  170. :param query: Existing query parameters (optional)
  171. :return: Combined results of paginated queries
  172. '''
  173. results = []
  174. # initalize query if it was called with None
  175. if not query:
  176. query = {}
  177. page = 0
  178. query['max'] = self.PAGE_SIZE
  179. # fetch until we can
  180. while True:
  181. query['first'] = page*self.PAGE_SIZE
  182. partial_results = raise_error_from_response(
  183. self.raw_get(url, **query),
  184. KeycloakGetError)
  185. if not partial_results:
  186. break
  187. results.extend(partial_results)
  188. if len(partial_results) < query['max']:
  189. break
  190. page += 1
  191. return results
  192. def import_realm(self, payload):
  193. """
  194. Import a new realm from a RealmRepresentation. Realm name must be unique.
  195. RealmRepresentation
  196. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  197. :param payload: RealmRepresentation
  198. :return: RealmRepresentation
  199. """
  200. data_raw = self.raw_post(URL_ADMIN_REALMS,
  201. data=json.dumps(payload))
  202. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  203. def export_realm(self, export_clients=False, export_groups_and_role=False):
  204. """
  205. Export the realm configurations in the json format
  206. RealmRepresentation
  207. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_partialexport
  208. :param export-clients: Skip if not want to export realm clients
  209. :param export-groups-and-roles: Skip if not want to export realm groups and roles
  210. :return: realm configurations JSON
  211. """
  212. params_path = {"realm-name": self.realm_name, "export-clients": export_clients, "export-groups-and-roles": export_groups_and_role }
  213. data_raw = self.raw_post(URL_ADMIN_REALM_EXPORT.format(**params_path), data="")
  214. return raise_error_from_response(data_raw, KeycloakGetError)
  215. def get_realms(self):
  216. """
  217. Lists all realms in Keycloak deployment
  218. :return: realms list
  219. """
  220. data_raw = self.raw_get(URL_ADMIN_REALMS)
  221. return raise_error_from_response(data_raw, KeycloakGetError)
  222. def create_realm(self, payload, skip_exists=False):
  223. """
  224. Create a realm
  225. RealmRepresentation:
  226. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  227. :param payload: RealmRepresentation
  228. :param skip_exists: Skip if Realm already exist.
  229. :return: Keycloak server response (RealmRepresentation)
  230. """
  231. data_raw = self.raw_post(URL_ADMIN_REALMS,
  232. data=json.dumps(payload))
  233. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  234. def update_realm(self, realm_name, payload):
  235. """
  236. Update a realm. This wil only update top level attributes and will ignore any user,
  237. role, or client information in the payload.
  238. RealmRepresentation:
  239. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  240. :param realm_name: Realm name (not the realm id)
  241. :param payload: RealmRepresentation
  242. :return: Http response
  243. """
  244. params_path = {"realm-name": realm_name}
  245. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  246. data=json.dumps(payload))
  247. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  248. def delete_realm(self, realm_name):
  249. """
  250. Delete a realm
  251. :param realm_name: Realm name (not the realm id)
  252. :return: Http response
  253. """
  254. params_path = {"realm-name": realm_name}
  255. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  256. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  257. def get_users(self, query=None):
  258. """
  259. Return a list of users, filtered according to query parameters
  260. UserRepresentation
  261. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  262. :param query: Query parameters (optional)
  263. :return: users list
  264. """
  265. params_path = {"realm-name": self.realm_name}
  266. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  267. def create_idp(self, payload):
  268. """
  269. Create an ID Provider,
  270. IdentityProviderRepresentation
  271. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  272. :param: payload: IdentityProviderRepresentation
  273. """
  274. params_path = {"realm-name": self.realm_name}
  275. data_raw = self.raw_post(URL_ADMIN_IDPS.format(**params_path),
  276. data=json.dumps(payload))
  277. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  278. def add_mapper_to_idp(self, idp_alias, payload):
  279. """
  280. Create an ID Provider,
  281. IdentityProviderRepresentation
  282. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityprovidermapperrepresentation
  283. :param: idp_alias: alias for Idp to add mapper in
  284. :param: payload: IdentityProviderMapperRepresentation
  285. """
  286. params_path = {"realm-name": self.realm_name, "idp-alias": idp_alias}
  287. data_raw = self.raw_post(URL_ADMIN_IDP_MAPPERS.format(**params_path),
  288. data=json.dumps(payload))
  289. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  290. def get_idps(self):
  291. """
  292. Returns a list of ID Providers,
  293. IdentityProviderRepresentation
  294. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  295. :return: array IdentityProviderRepresentation
  296. """
  297. params_path = {"realm-name": self.realm_name}
  298. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  299. return raise_error_from_response(data_raw, KeycloakGetError)
  300. def delete_idp(self, idp_alias):
  301. """
  302. Deletes ID Provider,
  303. :param: idp_alias: idp alias name
  304. """
  305. params_path = {"realm-name": self.realm_name, "alias": idp_alias}
  306. data_raw = self.raw_delete(URL_ADMIN_IDP.format(**params_path))
  307. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  308. def create_user(self, payload, exist_ok=True):
  309. """
  310. Create a new user. Username must be unique
  311. UserRepresentation
  312. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  313. :param payload: UserRepresentation
  314. :param exist_ok: If False, raise KeycloakGetError if username already exists. Otherwise, return existing user ID.
  315. :return: UserRepresentation
  316. """
  317. params_path = {"realm-name": self.realm_name}
  318. if exist_ok:
  319. exists = self.get_user_id(username=payload['username'])
  320. if exists is not None:
  321. return str(exists)
  322. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  323. data=json.dumps(payload))
  324. raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  325. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  326. return data_raw.headers['Location'][_last_slash_idx + 1:]
  327. def users_count(self):
  328. """
  329. User counter
  330. :return: counter
  331. """
  332. params_path = {"realm-name": self.realm_name}
  333. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  334. return raise_error_from_response(data_raw, KeycloakGetError)
  335. def get_user_id(self, username):
  336. """
  337. Get internal keycloak user id from username
  338. This is required for further actions against this user.
  339. UserRepresentation
  340. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  341. :param username: id in UserRepresentation
  342. :return: user_id
  343. """
  344. lower_user_name = username.lower()
  345. users = self.get_users(query={"search": lower_user_name})
  346. return next((user["id"] for user in users if user["username"] == lower_user_name), None)
  347. def get_user(self, user_id):
  348. """
  349. Get representation of the user
  350. :param user_id: User id
  351. UserRepresentation
  352. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  353. :return: UserRepresentation
  354. """
  355. params_path = {"realm-name": self.realm_name, "id": user_id}
  356. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  357. return raise_error_from_response(data_raw, KeycloakGetError)
  358. def get_user_groups(self, user_id):
  359. """
  360. Returns a list of groups of which the user is a member
  361. :param user_id: User id
  362. :return: user groups list
  363. """
  364. params_path = {"realm-name": self.realm_name, "id": user_id}
  365. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  366. return raise_error_from_response(data_raw, KeycloakGetError)
  367. def update_user(self, user_id, payload):
  368. """
  369. Update the user
  370. :param user_id: User id
  371. :param payload: UserRepresentation
  372. :return: Http response
  373. """
  374. params_path = {"realm-name": self.realm_name, "id": user_id}
  375. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  376. data=json.dumps(payload))
  377. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  378. def delete_user(self, user_id):
  379. """
  380. Delete the user
  381. :param user_id: User id
  382. :return: Http response
  383. """
  384. params_path = {"realm-name": self.realm_name, "id": user_id}
  385. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  386. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  387. def set_user_password(self, user_id, password, temporary=True):
  388. """
  389. Set up a password for the user. If temporary is True, the user will have to reset
  390. the temporary password next time they log in.
  391. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  392. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  393. :param user_id: User id
  394. :param password: New password
  395. :param temporary: True if password is temporary
  396. :return:
  397. """
  398. payload = {"type": "password", "temporary": temporary, "value": password}
  399. params_path = {"realm-name": self.realm_name, "id": user_id}
  400. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  401. data=json.dumps(payload))
  402. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  403. def logout(self, user_id):
  404. """
  405. Logs out user.
  406. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_logout
  407. :param user_id: User id
  408. :return:
  409. """
  410. params_path = {"realm-name": self.realm_name, "id": user_id}
  411. data_raw = self.raw_post(URL_ADMIN_USER_LOGOUT.format(**params_path), data="")
  412. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  413. def consents_user(self, user_id):
  414. """
  415. Get consents granted by the user
  416. :param user_id: User id
  417. :return: consents
  418. """
  419. params_path = {"realm-name": self.realm_name, "id": user_id}
  420. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  421. return raise_error_from_response(data_raw, KeycloakGetError)
  422. def get_user_social_logins(self, user_id):
  423. """
  424. Returns a list of federated identities/social logins of which the user has been associated with
  425. :param user_id: User id
  426. :return: federated identities list
  427. """
  428. params_path = {"realm-name": self.realm_name, "id": user_id}
  429. data_raw = self.raw_get(URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path))
  430. return raise_error_from_response(data_raw, KeycloakGetError)
  431. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  432. """
  433. Add a federated identity / social login provider to the user
  434. :param user_id: User id
  435. :param provider_id: Social login provider id
  436. :param provider_userid: userid specified by the provider
  437. :param provider_username: username specified by the provider
  438. :return:
  439. """
  440. payload = {"identityProvider": provider_id, "userId": provider_userid, "userName": provider_username}
  441. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  442. data_raw = self.raw_post(URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path), data=json.dumps(payload))
  443. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  444. """
  445. Send an update account email to the user. An email contains a
  446. link the user can click to perform a set of required actions.
  447. :param user_id: User id
  448. :param payload: A list of actions for the user to complete
  449. :param client_id: Client id (optional)
  450. :param lifespan: Number of seconds after which the generated token expires (optional)
  451. :param redirect_uri: The redirect uri (optional)
  452. :return:
  453. """
  454. params_path = {"realm-name": self.realm_name, "id": user_id}
  455. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  456. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  457. data=json.dumps(payload), **params_query)
  458. return raise_error_from_response(data_raw, KeycloakGetError)
  459. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  460. """
  461. Send a update account email to the user An email contains a
  462. link the user can click to perform a set of required actions.
  463. :param user_id: User id
  464. :param client_id: Client id (optional)
  465. :param redirect_uri: Redirect uri (optional)
  466. :return:
  467. """
  468. params_path = {"realm-name": self.realm_name, "id": user_id}
  469. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  470. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  471. data={}, **params_query)
  472. return raise_error_from_response(data_raw, KeycloakGetError)
  473. def get_sessions(self, user_id):
  474. """
  475. Get sessions associated with the user
  476. :param user_id: id of user
  477. UserSessionRepresentation
  478. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  479. :return: UserSessionRepresentation
  480. """
  481. params_path = {"realm-name": self.realm_name, "id": user_id}
  482. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  483. return raise_error_from_response(data_raw, KeycloakGetError)
  484. def get_server_info(self):
  485. """
  486. Get themes, social providers, auth providers, and event listeners available on this server
  487. ServerInfoRepresentation
  488. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  489. :return: ServerInfoRepresentation
  490. """
  491. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  492. return raise_error_from_response(data_raw, KeycloakGetError)
  493. def get_groups(self):
  494. """
  495. Returns a list of groups belonging to the realm
  496. GroupRepresentation
  497. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  498. :return: array GroupRepresentation
  499. """
  500. params_path = {"realm-name": self.realm_name}
  501. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  502. def get_group(self, group_id):
  503. """
  504. Get group by id. Returns full group details
  505. GroupRepresentation
  506. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  507. :param group_id: The group id
  508. :return: Keycloak server response (GroupRepresentation)
  509. """
  510. params_path = {"realm-name": self.realm_name, "id": group_id}
  511. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  512. return raise_error_from_response(data_raw, KeycloakGetError)
  513. def get_subgroups(self, group, path):
  514. """
  515. Utility function to iterate through nested group structures
  516. GroupRepresentation
  517. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  518. :param name: group (GroupRepresentation)
  519. :param path: group path (string)
  520. :return: Keycloak server response (GroupRepresentation)
  521. """
  522. for subgroup in group["subGroups"]:
  523. if subgroup['path'] == path:
  524. return subgroup
  525. elif subgroup["subGroups"]:
  526. for subgroup in group["subGroups"]:
  527. result = self.get_subgroups(subgroup, path)
  528. if result:
  529. return result
  530. # went through the tree without hits
  531. return None
  532. def get_group_members(self, group_id, **query):
  533. """
  534. Get members by group id. Returns group members
  535. GroupRepresentation
  536. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  537. :param group_id: The group id
  538. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  539. :return: Keycloak server response (UserRepresentation)
  540. """
  541. params_path = {"realm-name": self.realm_name, "id": group_id}
  542. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  543. def get_group_by_path(self, path, search_in_subgroups=False):
  544. """
  545. Get group id based on name or path.
  546. A straight name or path match with a top-level group will return first.
  547. Subgroups are traversed, the first to match path (or name with path) is returned.
  548. GroupRepresentation
  549. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  550. :param path: group path
  551. :param search_in_subgroups: True if want search in the subgroups
  552. :return: Keycloak server response (GroupRepresentation)
  553. """
  554. groups = self.get_groups()
  555. # TODO: Review this code is necessary
  556. for group in groups:
  557. if group['path'] == path:
  558. return group
  559. elif search_in_subgroups and group["subGroups"]:
  560. for group in group["subGroups"]:
  561. if group['path'] == path:
  562. return group
  563. res = self.get_subgroups(group, path)
  564. if res != None:
  565. return res
  566. return None
  567. def create_group(self, payload, parent=None, skip_exists=False):
  568. """
  569. Creates a group in the Realm
  570. :param payload: GroupRepresentation
  571. :param parent: parent group's id. Required to create a sub-group.
  572. :param skip_exists: If true then do not raise an error if it already exists
  573. GroupRepresentation
  574. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  575. :return: Http response
  576. """
  577. if parent is None:
  578. params_path = {"realm-name": self.realm_name}
  579. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  580. data=json.dumps(payload))
  581. else:
  582. params_path = {"realm-name": self.realm_name, "id": parent, }
  583. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  584. data=json.dumps(payload))
  585. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  586. def update_group(self, group_id, payload):
  587. """
  588. Update group, ignores subgroups.
  589. :param group_id: id of group
  590. :param payload: GroupRepresentation with updated information.
  591. GroupRepresentation
  592. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  593. :return: Http response
  594. """
  595. params_path = {"realm-name": self.realm_name, "id": group_id}
  596. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  597. data=json.dumps(payload))
  598. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  599. def group_set_permissions(self, group_id, enabled=True):
  600. """
  601. Enable/Disable permissions for a group. Cannot delete group if disabled
  602. :param group_id: id of group
  603. :param enabled: boolean
  604. :return: Keycloak server response
  605. """
  606. params_path = {"realm-name": self.realm_name, "id": group_id}
  607. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  608. data=json.dumps({"enabled": enabled}))
  609. return raise_error_from_response(data_raw, KeycloakGetError)
  610. def group_user_add(self, user_id, group_id):
  611. """
  612. Add user to group (user_id and group_id)
  613. :param user_id: id of user
  614. :param group_id: id of group to add to
  615. :return: Keycloak server response
  616. """
  617. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  618. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  619. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  620. def group_user_remove(self, user_id, group_id):
  621. """
  622. Remove user from group (user_id and group_id)
  623. :param user_id: id of user
  624. :param group_id: id of group to remove from
  625. :return: Keycloak server response
  626. """
  627. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  628. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  629. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  630. def delete_group(self, group_id):
  631. """
  632. Deletes a group in the Realm
  633. :param group_id: id of group to delete
  634. :return: Keycloak server response
  635. """
  636. params_path = {"realm-name": self.realm_name, "id": group_id}
  637. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  638. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  639. def get_clients(self):
  640. """
  641. Returns a list of clients belonging to the realm
  642. ClientRepresentation
  643. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  644. :return: Keycloak server response (ClientRepresentation)
  645. """
  646. params_path = {"realm-name": self.realm_name}
  647. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  648. return raise_error_from_response(data_raw, KeycloakGetError)
  649. def get_client(self, client_id):
  650. """
  651. Get representation of the client
  652. ClientRepresentation
  653. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  654. :param client_id: id of client (not client-id)
  655. :return: Keycloak server response (ClientRepresentation)
  656. """
  657. params_path = {"realm-name": self.realm_name, "id": client_id}
  658. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  659. return raise_error_from_response(data_raw, KeycloakGetError)
  660. def get_client_id(self, client_name):
  661. """
  662. Get internal keycloak client id from client-id.
  663. This is required for further actions against this client.
  664. :param client_name: name in ClientRepresentation
  665. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  666. :return: client_id (uuid as string)
  667. """
  668. clients = self.get_clients()
  669. for client in clients:
  670. if client_name == client.get('name') or client_name == client.get('clientId'):
  671. return client["id"]
  672. return None
  673. def get_client_authz_settings(self, client_id):
  674. """
  675. Get authorization json from client.
  676. :param client_id: id in ClientRepresentation
  677. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  678. :return: Keycloak server response
  679. """
  680. params_path = {"realm-name": self.realm_name, "id": client_id}
  681. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  682. return data_raw
  683. def create_client_authz_resource(self, client_id, payload, skip_exists=False):
  684. """
  685. Create resources of client.
  686. :param client_id: id in ClientRepresentation
  687. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  688. :return: Keycloak server response
  689. """
  690. params_path = {"realm-name": self.realm_name,
  691. "id": client_id}
  692. data_raw = self.raw_post(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path),
  693. data=json.dumps(payload))
  694. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  695. def get_client_authz_resources(self, client_id):
  696. """
  697. Get resources from client.
  698. :param client_id: id in ClientRepresentation
  699. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  700. :return: Keycloak server response
  701. """
  702. params_path = {"realm-name": self.realm_name, "id": client_id}
  703. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  704. return raise_error_from_response(data_raw, KeycloakGetError)
  705. def create_client_authz_role_based_policy(self, client_id, payload, skip_exists=False):
  706. """
  707. Create role-based policy of client.
  708. :param client_id: id in ClientRepresentation
  709. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  710. :return: Keycloak server response
  711. """
  712. params_path = {"realm-name": self.realm_name,
  713. "id": client_id}
  714. data_raw = self.raw_post(URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_POLICY.format(**params_path),
  715. data=json.dumps(payload))
  716. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  717. def create_client_authz_role_based_permission(self, client_id, payload, skip_exists=False):
  718. """
  719. Create role-based permission of client.
  720. :param client_id: id in ClientRepresentation
  721. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  722. :return: Keycloak server response
  723. """
  724. params_path = {"realm-name": self.realm_name,
  725. "id": client_id}
  726. data_raw = self.raw_post(URL_ADMIN_CLIENT_AUTHZ_ROLE_BASED_PERMISSION.format(**params_path),
  727. data=json.dumps(payload))
  728. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  729. def get_client_authz_policies(self, client_id):
  730. """
  731. Get policies from client.
  732. :param client_id: id in ClientRepresentation
  733. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  734. :return: Keycloak server response
  735. """
  736. params_path = {"realm-name": self.realm_name, "id": client_id}
  737. params_query = {"first": 0, "max": 20, "permission": False}
  738. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_POLICIES.format(**params_path), **params_query)
  739. return raise_error_from_response(data_raw, KeycloakGetError)
  740. def get_client_service_account_user(self, client_id):
  741. """
  742. Get service account user from client.
  743. :param client_id: id in ClientRepresentation
  744. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  745. :return: UserRepresentation
  746. """
  747. params_path = {"realm-name": self.realm_name, "id": client_id}
  748. data_raw = self.raw_get(URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path))
  749. return raise_error_from_response(data_raw, KeycloakGetError)
  750. def create_client(self, payload, skip_exists=False):
  751. """
  752. Create a client
  753. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  754. :param skip_exists: If true then do not raise an error if client already exists
  755. :param payload: ClientRepresentation
  756. :return: Keycloak server response (UserRepresentation)
  757. """
  758. params_path = {"realm-name": self.realm_name}
  759. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  760. data=json.dumps(payload))
  761. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  762. def update_client(self, client_id, payload):
  763. """
  764. Update a client
  765. :param client_id: Client id
  766. :param payload: ClientRepresentation
  767. :return: Http response
  768. """
  769. params_path = {"realm-name": self.realm_name, "id": client_id}
  770. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  771. data=json.dumps(payload))
  772. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  773. def delete_client(self, client_id):
  774. """
  775. Get representation of the client
  776. ClientRepresentation
  777. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  778. :param client_id: keycloak client id (not oauth client-id)
  779. :return: Keycloak server response (ClientRepresentation)
  780. """
  781. params_path = {"realm-name": self.realm_name, "id": client_id}
  782. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  783. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  784. def get_client_installation_provider(self, client_id, provider_id):
  785. """
  786. Get content for given installation provider
  787. Related documentation:
  788. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_clients_resource
  789. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  790. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_serverinforepresentation
  791. :param client_id: Client id
  792. :param provider_id: provider id to specify response format
  793. """
  794. params_path = {"realm-name": self.realm_name, "id": client_id, "provider-id": provider_id}
  795. data_raw = self.raw_get(URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path))
  796. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  797. def get_realm_roles(self):
  798. """
  799. Get all roles for the realm or client
  800. RoleRepresentation
  801. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  802. :return: Keycloak server response (RoleRepresentation)
  803. """
  804. params_path = {"realm-name": self.realm_name}
  805. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  806. return raise_error_from_response(data_raw, KeycloakGetError)
  807. def get_realm_role_members(self, role_name, **query):
  808. """
  809. Get role members of realm by role name.
  810. :param role_name: Name of the role.
  811. :param query: Additional Query parameters (see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_roles_resource)
  812. :return: Keycloak Server Response (UserRepresentation)
  813. """
  814. params_path = {"realm-name": self.realm_name, "role-name":role_name}
  815. return self.__fetch_all(URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query)
  816. def get_client_roles(self, client_id):
  817. """
  818. Get all roles for the client
  819. :param client_id: id of client (not client-id)
  820. RoleRepresentation
  821. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  822. :return: Keycloak server response (RoleRepresentation)
  823. """
  824. params_path = {"realm-name": self.realm_name, "id": client_id}
  825. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  826. return raise_error_from_response(data_raw, KeycloakGetError)
  827. def get_client_role(self, client_id, role_name):
  828. """
  829. Get client role id by name
  830. This is required for further actions with this role.
  831. :param client_id: id of client (not client-id)
  832. :param role_name: roles name (not id!)
  833. RoleRepresentation
  834. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  835. :return: role_id
  836. """
  837. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  838. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  839. return raise_error_from_response(data_raw, KeycloakGetError)
  840. def get_client_role_id(self, client_id, role_name):
  841. """
  842. Warning: Deprecated
  843. Get client role id by name
  844. This is required for further actions with this role.
  845. :param client_id: id of client (not client-id)
  846. :param role_name: roles name (not id!)
  847. RoleRepresentation
  848. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  849. :return: role_id
  850. """
  851. role = self.get_client_role(client_id, role_name)
  852. return role.get("id")
  853. def create_client_role(self, client_role_id, payload, skip_exists=False):
  854. """
  855. Create a client role
  856. RoleRepresentation
  857. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  858. :param client_role_id: id of client (not client-id)
  859. :param payload: RoleRepresentation
  860. :param skip_exists: If true then do not raise an error if client role already exists
  861. :return: Keycloak server response (RoleRepresentation)
  862. """
  863. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  864. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  865. data=json.dumps(payload))
  866. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  867. def add_composite_client_roles_to_role(self, client_role_id, role_name, roles):
  868. """
  869. Add composite roles to client role
  870. :param client_role_id: id of client (not client-id)
  871. :param role_name: The name of the role
  872. :param roles: roles list or role (use RoleRepresentation) to be updated
  873. :return Keycloak server response
  874. """
  875. payload = roles if isinstance(roles, list) else [roles]
  876. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  877. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE.format(**params_path),
  878. data=json.dumps(payload))
  879. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  880. def delete_client_role(self, client_role_id, role_name):
  881. """
  882. Delete a client role
  883. RoleRepresentation
  884. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  885. :param client_role_id: id of client (not client-id)
  886. :param role_name: roles name (not id!)
  887. """
  888. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  889. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  890. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  891. def assign_client_role(self, user_id, client_id, roles):
  892. """
  893. Assign a client role to a user
  894. :param user_id: id of user
  895. :param client_id: id of client (not client-id)
  896. :param roles: roles list or role (use RoleRepresentation)
  897. :return Keycloak server response
  898. """
  899. payload = roles if isinstance(roles, list) else [roles]
  900. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  901. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  902. data=json.dumps(payload))
  903. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  904. def get_client_role_members(self, client_id, role_name, **query):
  905. """
  906. Get members by client role .
  907. :param client_id: The client id
  908. :param role_name: the name of role to be queried.
  909. :param query: Additional query parameters ( see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_clients_resource)
  910. :return: Keycloak server response (UserRepresentation)
  911. """
  912. params_path = {"realm-name": self.realm_name, "id":client_id, "role-name":role_name}
  913. return self.__fetch_all(URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path) , query)
  914. def create_realm_role(self, payload, skip_exists=False):
  915. """
  916. Create a new role for the realm or client
  917. :param payload: The role (use RoleRepresentation)
  918. :param skip_exists: If true then do not raise an error if realm role already exists
  919. :return Keycloak server response
  920. """
  921. params_path = {"realm-name": self.realm_name}
  922. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  923. data=json.dumps(payload))
  924. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  925. def get_realm_role(self, role_name):
  926. """
  927. Get realm role by role name
  928. :param role_name: role's name, not id!
  929. RoleRepresentation
  930. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  931. :return: role_id
  932. """
  933. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  934. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  935. return raise_error_from_response(data_raw, KeycloakGetError)
  936. def update_realm_role(self, role_name, payload):
  937. """
  938. Update a role for the realm by name
  939. :param role_name: The name of the role to be updated
  940. :param payload: The role (use RoleRepresentation)
  941. :return Keycloak server response
  942. """
  943. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  944. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  945. data=json.dumps(payload))
  946. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  947. def delete_realm_role(self, role_name):
  948. """
  949. Delete a role for the realm by name
  950. :param payload: The role name {'role-name':'name-of-the-role'}
  951. :return Keycloak server response
  952. """
  953. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  954. data_raw = self.connection.raw_delete(
  955. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  956. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  957. def add_composite_realm_roles_to_role(self, role_name, roles):
  958. """
  959. Add composite roles to the role
  960. :param role_name: The name of the role
  961. :param roles: roles list or role (use RoleRepresentation) to be updated
  962. :return Keycloak server response
  963. """
  964. payload = roles if isinstance(roles, list) else [roles]
  965. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  966. data_raw = self.raw_post(
  967. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  968. data=json.dumps(payload))
  969. return raise_error_from_response(data_raw, KeycloakGetError,
  970. expected_codes=[204])
  971. def remove_composite_realm_roles_to_role(self, role_name, roles):
  972. """
  973. Remove composite roles from the role
  974. :param role_name: The name of the role
  975. :param roles: roles list or role (use RoleRepresentation) to be removed
  976. :return Keycloak server response
  977. """
  978. payload = roles if isinstance(roles, list) else [roles]
  979. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  980. data_raw = self.raw_delete(
  981. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  982. data=json.dumps(payload))
  983. return raise_error_from_response(data_raw, KeycloakGetError,
  984. expected_codes=[204])
  985. def get_composite_realm_roles_of_role(self, role_name):
  986. """
  987. Get composite roles of the role
  988. :param role_name: The name of the role
  989. :return Keycloak server response (array RoleRepresentation)
  990. """
  991. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  992. data_raw = self.raw_get(
  993. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  994. return raise_error_from_response(data_raw, KeycloakGetError)
  995. def assign_realm_roles(self, user_id, roles):
  996. """
  997. Assign realm roles to a user
  998. :param user_id: id of user
  999. :param client_id: id of client containing role (not client-id)
  1000. :param roles: roles list or role (use RoleRepresentation)
  1001. :return Keycloak server response
  1002. """
  1003. payload = roles if isinstance(roles, list) else [roles]
  1004. params_path = {"realm-name": self.realm_name, "id": user_id}
  1005. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  1006. data=json.dumps(payload))
  1007. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1008. def get_realm_roles_of_user(self, user_id):
  1009. """
  1010. Get all realm roles for a user.
  1011. :param user_id: id of user
  1012. :return: Keycloak server response (array RoleRepresentation)
  1013. """
  1014. params_path = {"realm-name": self.realm_name, "id": user_id}
  1015. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  1016. return raise_error_from_response(data_raw, KeycloakGetError)
  1017. def assign_group_realm_roles(self, group_id, roles):
  1018. """
  1019. Assign realm roles to a group
  1020. :param group_id: id of groupp
  1021. :param roles: roles list or role (use GroupRoleRepresentation)
  1022. :return Keycloak server response
  1023. """
  1024. payload = roles if isinstance(roles, list) else [roles]
  1025. params_path = {"realm-name": self.realm_name, "id": group_id}
  1026. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  1027. data=json.dumps(payload))
  1028. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1029. def delete_group_realm_roles(self, group_id, roles):
  1030. """
  1031. Delete realm roles of a group
  1032. :param group_id: id of group
  1033. :param roles: roles list or role (use GroupRoleRepresentation)
  1034. :return Keycloak server response
  1035. """
  1036. payload = roles if isinstance(roles, list) else [roles]
  1037. params_path = {"realm-name": self.realm_name, "id": group_id}
  1038. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  1039. data=json.dumps(payload))
  1040. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1041. def get_group_realm_roles(self, group_id):
  1042. """
  1043. Get all realm roles for a group.
  1044. :param user_id: id of the group
  1045. :return: Keycloak server response (array RoleRepresentation)
  1046. """
  1047. params_path = {"realm-name": self.realm_name, "id": group_id}
  1048. data_raw = self.raw_get(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path))
  1049. return raise_error_from_response(data_raw, KeycloakGetError)
  1050. def assign_group_client_roles(self, group_id, client_id, roles):
  1051. """
  1052. Assign client roles to a group
  1053. :param group_id: id of group
  1054. :param client_id: id of client (not client-id)
  1055. :param roles: roles list or role (use GroupRoleRepresentation)
  1056. :return Keycloak server response
  1057. """
  1058. payload = roles if isinstance(roles, list) else [roles]
  1059. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1060. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1061. data=json.dumps(payload))
  1062. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1063. def get_group_client_roles(self, group_id, client_id):
  1064. """
  1065. Get client roles of a group
  1066. :param group_id: id of group
  1067. :param client_id: id of client (not client-id)
  1068. :return Keycloak server response
  1069. """
  1070. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1071. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  1072. return raise_error_from_response(data_raw, KeycloakGetError)
  1073. def delete_group_client_roles(self, group_id, client_id, roles):
  1074. """
  1075. Delete client roles of a group
  1076. :param group_id: id of group
  1077. :param client_id: id of client (not client-id)
  1078. :param roles: roles list or role (use GroupRoleRepresentation)
  1079. :return Keycloak server response (array RoleRepresentation)
  1080. """
  1081. payload = roles if isinstance(roles, list) else [roles]
  1082. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1083. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1084. data=json.dumps(payload))
  1085. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1086. def get_client_roles_of_user(self, user_id, client_id):
  1087. """
  1088. Get all client roles for a user.
  1089. :param user_id: id of user
  1090. :param client_id: id of client (not client-id)
  1091. :return: Keycloak server response (array RoleRepresentation)
  1092. """
  1093. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1094. def get_available_client_roles_of_user(self, user_id, client_id):
  1095. """
  1096. Get available client role-mappings for a user.
  1097. :param user_id: id of user
  1098. :param client_id: id of client (not client-id)
  1099. :return: Keycloak server response (array RoleRepresentation)
  1100. """
  1101. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1102. def get_composite_client_roles_of_user(self, user_id, client_id):
  1103. """
  1104. Get composite client role-mappings for a user.
  1105. :param user_id: id of user
  1106. :param client_id: id of client (not client-id)
  1107. :return: Keycloak server response (array RoleRepresentation)
  1108. """
  1109. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1110. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1111. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1112. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1113. return raise_error_from_response(data_raw, KeycloakGetError)
  1114. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1115. """
  1116. Delete client roles from a user.
  1117. :param user_id: id of user
  1118. :param client_id: id of client containing role (not client-id)
  1119. :param roles: roles list or role to delete (use RoleRepresentation)
  1120. :return: Keycloak server response
  1121. """
  1122. payload = roles if isinstance(roles, list) else [roles]
  1123. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1124. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1125. data=json.dumps(payload))
  1126. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1127. def get_authentication_flows(self):
  1128. """
  1129. Get authentication flows. Returns all flow details
  1130. AuthenticationFlowRepresentation
  1131. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1132. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1133. """
  1134. params_path = {"realm-name": self.realm_name}
  1135. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1136. return raise_error_from_response(data_raw, KeycloakGetError)
  1137. def get_authentication_flow_for_id(self, flow_id):
  1138. """
  1139. Get one authentication flow by it's id/alias. Returns all flow details
  1140. AuthenticationFlowRepresentation
  1141. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1142. :param flow_id: the id of a flow NOT it's alias
  1143. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1144. """
  1145. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1146. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1147. return raise_error_from_response(data_raw, KeycloakGetError)
  1148. def create_authentication_flow(self, payload, skip_exists=False):
  1149. """
  1150. Create a new authentication flow
  1151. AuthenticationFlowRepresentation
  1152. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1153. :param payload: AuthenticationFlowRepresentation
  1154. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1155. :return: Keycloak server response (RoleRepresentation)
  1156. """
  1157. params_path = {"realm-name": self.realm_name}
  1158. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1159. data=json.dumps(payload))
  1160. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1161. def copy_authentication_flow(self, payload, flow_alias):
  1162. """
  1163. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1164. :param payload: JSON containing 'newName' attribute
  1165. :param flow_alias: the flow alias
  1166. :return: Keycloak server response (RoleRepresentation)
  1167. """
  1168. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1169. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1170. data=json.dumps(payload))
  1171. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1172. def get_authentication_flow_executions(self, flow_alias):
  1173. """
  1174. Get authentication flow executions. Returns all execution steps
  1175. :param flow_alias: the flow alias
  1176. :return: Response(json)
  1177. """
  1178. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1179. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1180. return raise_error_from_response(data_raw, KeycloakGetError)
  1181. def update_authentication_flow_executions(self, payload, flow_alias):
  1182. """
  1183. Update an authentication flow execution
  1184. AuthenticationExecutionInfoRepresentation
  1185. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1186. :param payload: AuthenticationExecutionInfoRepresentation
  1187. :param flow_alias: The flow alias
  1188. :return: Keycloak server response
  1189. """
  1190. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1191. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1192. data=json.dumps(payload))
  1193. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1194. def create_authentication_flow_execution(self, payload, flow_alias):
  1195. """
  1196. Create an authentication flow execution
  1197. AuthenticationExecutionInfoRepresentation
  1198. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1199. :param payload: AuthenticationExecutionInfoRepresentation
  1200. :param flow_alias: The flow alias
  1201. :return: Keycloak server response
  1202. """
  1203. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1204. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1205. data=json.dumps(payload))
  1206. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1207. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1208. """
  1209. Create a new sub authentication flow for a given authentication flow
  1210. AuthenticationFlowRepresentation
  1211. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1212. :param payload: AuthenticationFlowRepresentation
  1213. :param flow_alias: The flow alias
  1214. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1215. :return: Keycloak server response (RoleRepresentation)
  1216. """
  1217. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1218. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1219. data=json.dumps(payload))
  1220. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1221. def get_authenticator_config(self, config_id):
  1222. """
  1223. Get authenticator configuration. Returns all configuration details.
  1224. :param config_id: Authenticator config id
  1225. :return: Response(json)
  1226. """
  1227. params_path = {"realm-name": self.realm_name, "id": config_id}
  1228. data_raw = self.raw_get(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1229. return raise_error_from_response(data_raw, KeycloakGetError)
  1230. def update_authenticator_config(self, payload, config_id):
  1231. """
  1232. Update an authenticator configuration.
  1233. AuthenticatorConfigRepresentation
  1234. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticatorconfigrepresentation
  1235. :param payload: AuthenticatorConfigRepresentation
  1236. :param config_id: Authenticator config id
  1237. :return: Response(json)
  1238. """
  1239. params_path = {"realm-name": self.realm_name, "id": config_id}
  1240. data_raw = self.raw_put(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1241. data=json.dumps(payload))
  1242. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1243. def delete_authenticator_config(self, config_id):
  1244. """
  1245. Delete a authenticator configuration.
  1246. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource
  1247. :param config_id: Authenticator config id
  1248. :return: Keycloak server Response
  1249. """
  1250. params_path = {"realm-name": self.realm_name, "id": config_id}
  1251. data_raw = self.raw_delete(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1252. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1253. def sync_users(self, storage_id, action):
  1254. """
  1255. Function to trigger user sync from provider
  1256. :param storage_id: The id of the user storage provider
  1257. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1258. :return:
  1259. """
  1260. data = {'action': action}
  1261. params_query = {"action": action}
  1262. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1263. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1264. data=json.dumps(data), **params_query)
  1265. return raise_error_from_response(data_raw, KeycloakGetError)
  1266. def get_client_scopes(self):
  1267. """
  1268. Get representation of the client scopes for the realm where we are connected to
  1269. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1270. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1271. """
  1272. params_path = {"realm-name": self.realm_name}
  1273. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1274. return raise_error_from_response(data_raw, KeycloakGetError)
  1275. def get_client_scope(self, client_scope_id):
  1276. """
  1277. Get representation of the client scopes for the realm where we are connected to
  1278. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1279. :param client_scope_id: The id of the client scope
  1280. :return: Keycloak server response (ClientScopeRepresentation)
  1281. """
  1282. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1283. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1284. return raise_error_from_response(data_raw, KeycloakGetError)
  1285. def create_client_scope(self, payload, skip_exists=False):
  1286. """
  1287. Create a client scope
  1288. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1289. :param payload: ClientScopeRepresentation
  1290. :param skip_exists: If true then do not raise an error if client scope already exists
  1291. :return: Keycloak server response (ClientScopeRepresentation)
  1292. """
  1293. params_path = {"realm-name": self.realm_name}
  1294. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1295. data=json.dumps(payload))
  1296. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1297. def update_client_scope(self, client_scope_id, payload):
  1298. """
  1299. Update a client scope
  1300. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_client_scopes_resource
  1301. :param client_scope_id: The id of the client scope
  1302. :param payload: ClientScopeRepresentation
  1303. :return: Keycloak server response (ClientScopeRepresentation)
  1304. """
  1305. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1306. data_raw = self.raw_put(URL_ADMIN_CLIENT_SCOPE.format(**params_path),
  1307. data=json.dumps(payload))
  1308. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1309. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1310. """
  1311. Add a mapper to a client scope
  1312. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1313. :param client_scope_id: The id of the client scope
  1314. :param payload: ProtocolMapperRepresentation
  1315. :return: Keycloak server Response
  1316. """
  1317. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1318. data_raw = self.raw_post(
  1319. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1320. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1321. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1322. """
  1323. Delete a mapper from a client scope
  1324. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1325. :param client_scope_id: The id of the client scope
  1326. :param payload: ProtocolMapperRepresentation
  1327. :return: Keycloak server Response
  1328. """
  1329. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1330. "protocol-mapper-id": protocol_mppaer_id}
  1331. data_raw = self.raw_delete(
  1332. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1333. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1334. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  1335. """
  1336. Update an existing protocol mapper in a client scope
  1337. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_protocol_mappers_resource
  1338. :param client_scope_id: The id of the client scope
  1339. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  1340. and should to be updated
  1341. :param payload: ProtocolMapperRepresentation
  1342. :return: Keycloak server Response
  1343. """
  1344. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1345. "protocol-mapper-id": protocol_mapper_id}
  1346. data_raw = self.raw_put(
  1347. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path), data=json.dumps(payload))
  1348. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1349. def add_mapper_to_client(self, client_id, payload):
  1350. """
  1351. Add a mapper to a client
  1352. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1353. :param client_id: The id of the client
  1354. :param payload: ProtocolMapperRepresentation
  1355. :return: Keycloak server Response
  1356. """
  1357. params_path = {"realm-name": self.realm_name, "id": client_id}
  1358. data_raw = self.raw_post(
  1359. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1360. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1361. def generate_client_secrets(self, client_id):
  1362. """
  1363. Generate a new secret for the client
  1364. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1365. :param client_id: id of client (not client-id)
  1366. :return: Keycloak server response (ClientRepresentation)
  1367. """
  1368. params_path = {"realm-name": self.realm_name, "id": client_id}
  1369. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1370. return raise_error_from_response(data_raw, KeycloakGetError)
  1371. def get_client_secrets(self, client_id):
  1372. """
  1373. Get representation of the client secrets
  1374. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1375. :param client_id: id of client (not client-id)
  1376. :return: Keycloak server response (ClientRepresentation)
  1377. """
  1378. params_path = {"realm-name": self.realm_name, "id": client_id}
  1379. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1380. return raise_error_from_response(data_raw, KeycloakGetError)
  1381. def get_components(self, query=None):
  1382. """
  1383. Return a list of components, filtered according to query parameters
  1384. ComponentRepresentation
  1385. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1386. :param query: Query parameters (optional)
  1387. :return: components list
  1388. """
  1389. params_path = {"realm-name": self.realm_name}
  1390. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1391. data=None, **query)
  1392. return raise_error_from_response(data_raw, KeycloakGetError)
  1393. def create_component(self, payload):
  1394. """
  1395. Create a new component.
  1396. ComponentRepresentation
  1397. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1398. :param payload: ComponentRepresentation
  1399. :return: UserRepresentation
  1400. """
  1401. params_path = {"realm-name": self.realm_name}
  1402. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1403. data=json.dumps(payload))
  1404. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1405. def get_component(self, component_id):
  1406. """
  1407. Get representation of the component
  1408. :param component_id: Component id
  1409. ComponentRepresentation
  1410. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1411. :return: ComponentRepresentation
  1412. """
  1413. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1414. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1415. return raise_error_from_response(data_raw, KeycloakGetError)
  1416. def update_component(self, component_id, payload):
  1417. """
  1418. Update the component
  1419. :param component_id: Component id
  1420. :param payload: ComponentRepresentation
  1421. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1422. :return: Http response
  1423. """
  1424. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1425. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1426. data=json.dumps(payload))
  1427. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1428. def delete_component(self, component_id):
  1429. """
  1430. Delete the component
  1431. :param component_id: Component id
  1432. :return: Http response
  1433. """
  1434. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1435. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1436. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1437. def get_keys(self):
  1438. """
  1439. Return a list of keys, filtered according to query parameters
  1440. KeysMetadataRepresentation
  1441. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1442. :return: keys list
  1443. """
  1444. params_path = {"realm-name": self.realm_name}
  1445. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1446. data=None)
  1447. return raise_error_from_response(data_raw, KeycloakGetError)
  1448. def get_events(self, query=None):
  1449. """
  1450. Return a list of events, filtered according to query parameters
  1451. EventRepresentation array
  1452. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_eventrepresentation
  1453. :return: events list
  1454. """
  1455. params_path = {"realm-name": self.realm_name}
  1456. data_raw = self.raw_get(URL_ADMIN_EVENTS.format(**params_path),
  1457. data=None, **query)
  1458. return raise_error_from_response(data_raw, KeycloakGetError)
  1459. def set_events(self, payload):
  1460. """
  1461. Set realm events configuration
  1462. RealmEventsConfigRepresentation
  1463. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmeventsconfigrepresentation
  1464. :return: Http response
  1465. """
  1466. params_path = {"realm-name": self.realm_name}
  1467. data_raw = self.raw_put(URL_ADMIN_EVENTS.format(**params_path),
  1468. data=json.dumps(payload))
  1469. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1470. def raw_get(self, *args, **kwargs):
  1471. """
  1472. Calls connection.raw_get.
  1473. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1474. and try *get* once more.
  1475. """
  1476. r = self.connection.raw_get(*args, **kwargs)
  1477. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1478. self.refresh_token()
  1479. return self.connection.raw_get(*args, **kwargs)
  1480. return r
  1481. def raw_post(self, *args, **kwargs):
  1482. """
  1483. Calls connection.raw_post.
  1484. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1485. and try *post* once more.
  1486. """
  1487. r = self.connection.raw_post(*args, **kwargs)
  1488. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1489. self.refresh_token()
  1490. return self.connection.raw_post(*args, **kwargs)
  1491. return r
  1492. def raw_put(self, *args, **kwargs):
  1493. """
  1494. Calls connection.raw_put.
  1495. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1496. and try *put* once more.
  1497. """
  1498. r = self.connection.raw_put(*args, **kwargs)
  1499. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1500. self.refresh_token()
  1501. return self.connection.raw_put(*args, **kwargs)
  1502. return r
  1503. def raw_delete(self, *args, **kwargs):
  1504. """
  1505. Calls connection.raw_delete.
  1506. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1507. and try *delete* once more.
  1508. """
  1509. r = self.connection.raw_delete(*args, **kwargs)
  1510. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1511. self.refresh_token()
  1512. return self.connection.raw_delete(*args, **kwargs)
  1513. return r
  1514. def get_token(self):
  1515. token_realm_name = 'master' if self.client_secret_key else self.user_realm_name or self.realm_name
  1516. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1517. realm_name=token_realm_name, verify=self.verify,
  1518. client_secret_key=self.client_secret_key,
  1519. custom_headers=self.custom_headers)
  1520. grant_type = ["password"]
  1521. if self.client_secret_key:
  1522. grant_type = ["client_credentials"]
  1523. if self.user_realm_name:
  1524. self.realm_name = self.user_realm_name
  1525. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1526. headers = {
  1527. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1528. 'Content-Type': 'application/json'
  1529. }
  1530. if self.custom_headers is not None:
  1531. # merge custom headers to main headers
  1532. headers.update(self.custom_headers)
  1533. self._connection = ConnectionManager(base_url=self.server_url,
  1534. headers=headers,
  1535. timeout=60,
  1536. verify=self.verify)
  1537. def refresh_token(self):
  1538. refresh_token = self.token.get('refresh_token')
  1539. try:
  1540. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1541. except KeycloakGetError as e:
  1542. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1543. b'Token is not active' in e.response_body):
  1544. self.get_token()
  1545. else:
  1546. raise
  1547. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))
  1548. def get_client_all_sessions(self, client_id):
  1549. """
  1550. Get sessions associated with the client
  1551. :param client_id: id of client
  1552. UserSessionRepresentation
  1553. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  1554. :return: UserSessionRepresentation
  1555. """
  1556. params_path = {"realm-name": self.realm_name, "id": client_id}
  1557. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  1558. return raise_error_from_response(data_raw, KeycloakGetError)
  1559. def delete_user_realm_role(self, user_id, payload):
  1560. """
  1561. Delete realm-level role mappings
  1562. DELETE admin/realms/{realm-name}/users/{id}/role-mappings/realm
  1563. """
  1564. params_path = {"realm-name": self.realm_name, "id": str(user_id) }
  1565. data_raw = self.connection.raw_delete(URL_ADMIN_DELETE_USER_ROLE.format(**params_path),
  1566. data=json.dumps(payload))
  1567. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])