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.

1982 lines
78 KiB

7 years ago
7 years ago
6 years ago
4 years ago
6 years ago
7 years ago
6 years ago
4 years ago
4 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from builtins import isinstance
  27. from typing import 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_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_GROUPS_REALM_ROLES, \
  33. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE, URL_ADMIN_CLIENT_INSTALLATION_PROVIDER, \
  34. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GROUPS_CLIENT_ROLES, \
  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, URL_ADMIN_IDP, \
  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, URL_ADMIN_CLIENT_ROLE_MEMBERS, \
  44. URL_ADMIN_REALM_ROLES_MEMBERS, URL_ADMIN_CLIENT_PROTOCOL_MAPPER, URL_ADMIN_CLIENT_SCOPES_MAPPERS, \
  45. URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION, URL_ADMIN_FLOWS_EXECUTIONS_FLOW, URL_ADMIN_FLOWS_COPY, \
  46. URL_ADMIN_FLOWS_ALIAS, URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER, URL_ADMIN_AUTHENTICATOR_CONFIG, \
  47. URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE, URL_ADMIN_CLIENT_ALL_SESSIONS, URL_ADMIN_EVENTS, \
  48. URL_ADMIN_REALM_EXPORT, URL_ADMIN_DELETE_USER_ROLE, URL_ADMIN_USER_LOGOUT, URL_ADMIN_FLOWS_EXECUTION, \
  49. URL_ADMIN_FLOW
  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 get_client_authz_resources(self, client_id):
  684. """
  685. Get resources from 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, "id": client_id}
  691. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  692. return data_raw
  693. def get_client_service_account_user(self, client_id):
  694. """
  695. Get service account user from client.
  696. :param client_id: id in ClientRepresentation
  697. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  698. :return: UserRepresentation
  699. """
  700. params_path = {"realm-name": self.realm_name, "id": client_id}
  701. data_raw = self.raw_get(URL_ADMIN_CLIENT_SERVICE_ACCOUNT_USER.format(**params_path))
  702. return raise_error_from_response(data_raw, KeycloakGetError)
  703. def create_client(self, payload, skip_exists=False):
  704. """
  705. Create a client
  706. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  707. :param skip_exists: If true then do not raise an error if client already exists
  708. :param payload: ClientRepresentation
  709. :return: Keycloak server response (UserRepresentation)
  710. """
  711. params_path = {"realm-name": self.realm_name}
  712. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  713. data=json.dumps(payload))
  714. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  715. def update_client(self, client_id, payload):
  716. """
  717. Update a client
  718. :param client_id: Client id
  719. :param payload: ClientRepresentation
  720. :return: Http response
  721. """
  722. params_path = {"realm-name": self.realm_name, "id": client_id}
  723. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  724. data=json.dumps(payload))
  725. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  726. def delete_client(self, client_id):
  727. """
  728. Get representation of the client
  729. ClientRepresentation
  730. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  731. :param client_id: keycloak client id (not oauth client-id)
  732. :return: Keycloak server response (ClientRepresentation)
  733. """
  734. params_path = {"realm-name": self.realm_name, "id": client_id}
  735. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  736. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  737. def get_client_installation_provider(self, client_id, provider_id):
  738. """
  739. Get content for given installation provider
  740. Related documentation:
  741. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_clients_resource
  742. Possible provider_id list available in the ServerInfoRepresentation#clientInstallations
  743. https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_serverinforepresentation
  744. :param client_id: Client id
  745. :param provider_id: provider id to specify response format
  746. """
  747. params_path = {"realm-name": self.realm_name, "id": client_id, "provider-id": provider_id}
  748. data_raw = self.raw_get(URL_ADMIN_CLIENT_INSTALLATION_PROVIDER.format(**params_path))
  749. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[200])
  750. def get_realm_roles(self):
  751. """
  752. Get all roles for the realm or client
  753. RoleRepresentation
  754. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  755. :return: Keycloak server response (RoleRepresentation)
  756. """
  757. params_path = {"realm-name": self.realm_name}
  758. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  759. return raise_error_from_response(data_raw, KeycloakGetError)
  760. def get_realm_role_members(self, role_name, **query):
  761. """
  762. Get role members of realm by role name.
  763. :param role_name: Name of the role.
  764. :param query: Additional Query parameters (see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_roles_resource)
  765. :return: Keycloak Server Response (UserRepresentation)
  766. """
  767. params_path = {"realm-name": self.realm_name, "role-name":role_name}
  768. return self.__fetch_all(URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query)
  769. def get_client_roles(self, client_id):
  770. """
  771. Get all roles for the client
  772. :param client_id: id of client (not client-id)
  773. RoleRepresentation
  774. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  775. :return: Keycloak server response (RoleRepresentation)
  776. """
  777. params_path = {"realm-name": self.realm_name, "id": client_id}
  778. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  779. return raise_error_from_response(data_raw, KeycloakGetError)
  780. def get_client_role(self, client_id, role_name):
  781. """
  782. Get client role id by name
  783. This is required for further actions with this role.
  784. :param client_id: id of client (not client-id)
  785. :param role_name: roles name (not id!)
  786. RoleRepresentation
  787. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  788. :return: role_id
  789. """
  790. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  791. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  792. return raise_error_from_response(data_raw, KeycloakGetError)
  793. def get_client_role_id(self, client_id, role_name):
  794. """
  795. Warning: Deprecated
  796. Get client role id by name
  797. This is required for further actions with this role.
  798. :param client_id: id of client (not client-id)
  799. :param role_name: roles name (not id!)
  800. RoleRepresentation
  801. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  802. :return: role_id
  803. """
  804. role = self.get_client_role(client_id, role_name)
  805. return role.get("id")
  806. def create_client_role(self, client_role_id, payload, skip_exists=False):
  807. """
  808. Create a client role
  809. RoleRepresentation
  810. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  811. :param client_role_id: id of client (not client-id)
  812. :param payload: RoleRepresentation
  813. :param skip_exists: If true then do not raise an error if client role already exists
  814. :return: Keycloak server response (RoleRepresentation)
  815. """
  816. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  817. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  818. data=json.dumps(payload))
  819. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  820. def add_composite_client_roles_to_role(self, client_role_id, role_name, roles):
  821. """
  822. Add composite roles to client role
  823. :param client_role_id: id of client (not client-id)
  824. :param role_name: The name of the role
  825. :param roles: roles list or role (use RoleRepresentation) to be updated
  826. :return Keycloak server response
  827. """
  828. payload = roles if isinstance(roles, list) else [roles]
  829. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  830. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES_COMPOSITE_CLIENT_ROLE.format(**params_path),
  831. data=json.dumps(payload))
  832. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  833. def delete_client_role(self, client_role_id, role_name):
  834. """
  835. Delete a client role
  836. RoleRepresentation
  837. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  838. :param client_role_id: id of client (not client-id)
  839. :param role_name: roles name (not id!)
  840. """
  841. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  842. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  843. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  844. def assign_client_role(self, user_id, client_id, roles):
  845. """
  846. Assign a client role to a user
  847. :param user_id: id of user
  848. :param client_id: id of client (not client-id)
  849. :param roles: roles list or role (use RoleRepresentation)
  850. :return Keycloak server response
  851. """
  852. payload = roles if isinstance(roles, list) else [roles]
  853. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  854. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  855. data=json.dumps(payload))
  856. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  857. def get_client_role_members(self, client_id, role_name, **query):
  858. """
  859. Get members by client role .
  860. :param client_id: The client id
  861. :param role_name: the name of role to be queried.
  862. :param query: Additional query parameters ( see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_clients_resource)
  863. :return: Keycloak server response (UserRepresentation)
  864. """
  865. params_path = {"realm-name": self.realm_name, "id":client_id, "role-name":role_name}
  866. return self.__fetch_all(URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path) , query)
  867. def create_realm_role(self, payload, skip_exists=False):
  868. """
  869. Create a new role for the realm or client
  870. :param payload: The role (use RoleRepresentation)
  871. :param skip_exists: If true then do not raise an error if realm role already exists
  872. :return Keycloak server response
  873. """
  874. params_path = {"realm-name": self.realm_name}
  875. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  876. data=json.dumps(payload))
  877. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  878. def get_realm_role(self, role_name):
  879. """
  880. Get realm role by role name
  881. :param role_name: role's name, not id!
  882. RoleRepresentation
  883. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  884. :return: role_id
  885. """
  886. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  887. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  888. return raise_error_from_response(data_raw, KeycloakGetError)
  889. def update_realm_role(self, role_name, payload):
  890. """
  891. Update a role for the realm by name
  892. :param role_name: The name of the role to be updated
  893. :param payload: The role (use RoleRepresentation)
  894. :return Keycloak server response
  895. """
  896. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  897. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  898. data=json.dumps(payload))
  899. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  900. def delete_realm_role(self, role_name):
  901. """
  902. Delete a role for the realm by name
  903. :param payload: The role name {'role-name':'name-of-the-role'}
  904. :return Keycloak server response
  905. """
  906. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  907. data_raw = self.connection.raw_delete(
  908. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  909. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  910. def add_composite_realm_roles_to_role(self, role_name, roles):
  911. """
  912. Add composite roles to the role
  913. :param role_name: The name of the role
  914. :param roles: roles list or role (use RoleRepresentation) to be updated
  915. :return Keycloak server response
  916. """
  917. payload = roles if isinstance(roles, list) else [roles]
  918. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  919. data_raw = self.raw_post(
  920. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  921. data=json.dumps(payload))
  922. return raise_error_from_response(data_raw, KeycloakGetError,
  923. expected_codes=[204])
  924. def remove_composite_realm_roles_to_role(self, role_name, roles):
  925. """
  926. Remove composite roles from the role
  927. :param role_name: The name of the role
  928. :param roles: roles list or role (use RoleRepresentation) to be removed
  929. :return Keycloak server response
  930. """
  931. payload = roles if isinstance(roles, list) else [roles]
  932. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  933. data_raw = self.raw_delete(
  934. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  935. data=json.dumps(payload))
  936. return raise_error_from_response(data_raw, KeycloakGetError,
  937. expected_codes=[204])
  938. def get_composite_realm_roles_of_role(self, role_name):
  939. """
  940. Get composite roles of the role
  941. :param role_name: The name of the role
  942. :return Keycloak server response (array RoleRepresentation)
  943. """
  944. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  945. data_raw = self.raw_get(
  946. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  947. return raise_error_from_response(data_raw, KeycloakGetError)
  948. def assign_realm_roles(self, user_id, roles):
  949. """
  950. Assign realm roles to a user
  951. :param user_id: id of user
  952. :param client_id: id of client containing role (not client-id)
  953. :param roles: roles list or role (use RoleRepresentation)
  954. :return Keycloak server response
  955. """
  956. payload = roles if isinstance(roles, list) else [roles]
  957. params_path = {"realm-name": self.realm_name, "id": user_id}
  958. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  959. data=json.dumps(payload))
  960. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  961. def get_realm_roles_of_user(self, user_id):
  962. """
  963. Get all realm roles for a user.
  964. :param user_id: id of user
  965. :return: Keycloak server response (array RoleRepresentation)
  966. """
  967. params_path = {"realm-name": self.realm_name, "id": user_id}
  968. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  969. return raise_error_from_response(data_raw, KeycloakGetError)
  970. def assign_group_realm_roles(self, group_id, roles):
  971. """
  972. Assign realm roles to a group
  973. :param group_id: id of groupp
  974. :param roles: roles list or role (use GroupRoleRepresentation)
  975. :return Keycloak server response
  976. """
  977. payload = roles if isinstance(roles, list) else [roles]
  978. params_path = {"realm-name": self.realm_name, "id": group_id}
  979. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  980. data=json.dumps(payload))
  981. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  982. def delete_group_realm_roles(self, group_id, roles):
  983. """
  984. Delete realm roles of a group
  985. :param group_id: id of group
  986. :param roles: roles list or role (use GroupRoleRepresentation)
  987. :return Keycloak server response
  988. """
  989. payload = roles if isinstance(roles, list) else [roles]
  990. params_path = {"realm-name": self.realm_name, "id": group_id}
  991. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  992. data=json.dumps(payload))
  993. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  994. def get_group_realm_roles(self, group_id):
  995. """
  996. Get all realm roles for a group.
  997. :param user_id: id of the group
  998. :return: Keycloak server response (array RoleRepresentation)
  999. """
  1000. params_path = {"realm-name": self.realm_name, "id": group_id}
  1001. data_raw = self.raw_get(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path))
  1002. return raise_error_from_response(data_raw, KeycloakGetError)
  1003. def assign_group_client_roles(self, group_id, client_id, roles):
  1004. """
  1005. Assign client roles to a group
  1006. :param group_id: id of group
  1007. :param client_id: id of client (not client-id)
  1008. :param roles: roles list or role (use GroupRoleRepresentation)
  1009. :return Keycloak server response
  1010. """
  1011. payload = roles if isinstance(roles, list) else [roles]
  1012. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1013. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1014. data=json.dumps(payload))
  1015. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1016. def get_group_client_roles(self, group_id, client_id):
  1017. """
  1018. Get client roles of a group
  1019. :param group_id: id of group
  1020. :param client_id: id of client (not client-id)
  1021. :return Keycloak server response
  1022. """
  1023. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1024. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  1025. return raise_error_from_response(data_raw, KeycloakGetError)
  1026. def delete_group_client_roles(self, group_id, client_id, roles):
  1027. """
  1028. Delete client roles of a group
  1029. :param group_id: id of group
  1030. :param client_id: id of client (not client-id)
  1031. :param roles: roles list or role (use GroupRoleRepresentation)
  1032. :return Keycloak server response (array RoleRepresentation)
  1033. """
  1034. payload = roles if isinstance(roles, list) else [roles]
  1035. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1036. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1037. data=json.dumps(payload))
  1038. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1039. def get_client_roles_of_user(self, user_id, client_id):
  1040. """
  1041. Get all client roles for a user.
  1042. :param user_id: id of user
  1043. :param client_id: id of client (not client-id)
  1044. :return: Keycloak server response (array RoleRepresentation)
  1045. """
  1046. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1047. def get_available_client_roles_of_user(self, user_id, client_id):
  1048. """
  1049. Get available client role-mappings for a user.
  1050. :param user_id: id of user
  1051. :param client_id: id of client (not client-id)
  1052. :return: Keycloak server response (array RoleRepresentation)
  1053. """
  1054. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1055. def get_composite_client_roles_of_user(self, user_id, client_id):
  1056. """
  1057. Get composite client role-mappings for a user.
  1058. :param user_id: id of user
  1059. :param client_id: id of client (not client-id)
  1060. :return: Keycloak server response (array RoleRepresentation)
  1061. """
  1062. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1063. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1064. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1065. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1066. return raise_error_from_response(data_raw, KeycloakGetError)
  1067. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1068. """
  1069. Delete client roles from a user.
  1070. :param user_id: id of user
  1071. :param client_id: id of client containing role (not client-id)
  1072. :param roles: roles list or role to delete (use RoleRepresentation)
  1073. :return: Keycloak server response
  1074. """
  1075. payload = roles if isinstance(roles, list) else [roles]
  1076. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1077. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1078. data=json.dumps(payload))
  1079. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1080. def get_authentication_flows(self):
  1081. """
  1082. Get authentication flows. Returns all flow details
  1083. AuthenticationFlowRepresentation
  1084. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1085. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1086. """
  1087. params_path = {"realm-name": self.realm_name}
  1088. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1089. return raise_error_from_response(data_raw, KeycloakGetError)
  1090. def get_authentication_flow_for_id(self, flow_id):
  1091. """
  1092. Get one authentication flow by it's id/alias. Returns all flow details
  1093. AuthenticationFlowRepresentation
  1094. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1095. :param flow_id: the id of a flow NOT it's alias
  1096. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1097. """
  1098. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1099. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1100. return raise_error_from_response(data_raw, KeycloakGetError)
  1101. def create_authentication_flow(self, payload, skip_exists=False):
  1102. """
  1103. Create a new authentication flow
  1104. AuthenticationFlowRepresentation
  1105. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1106. :param payload: AuthenticationFlowRepresentation
  1107. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1108. :return: Keycloak server response (RoleRepresentation)
  1109. """
  1110. params_path = {"realm-name": self.realm_name}
  1111. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1112. data=json.dumps(payload))
  1113. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1114. def copy_authentication_flow(self, payload, flow_alias):
  1115. """
  1116. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1117. :param payload: JSON containing 'newName' attribute
  1118. :param flow_alias: the flow alias
  1119. :return: Keycloak server response (RoleRepresentation)
  1120. """
  1121. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1122. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1123. data=json.dumps(payload))
  1124. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1125. def delete_authentication_flow(self, flow_id):
  1126. """
  1127. Delete authentication flow
  1128. AuthenticationInfoRepresentation
  1129. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationinforepresentation
  1130. :param flow_id: authentication flow id
  1131. :return: Keycloak server response
  1132. """
  1133. params_path = {"realm-name": self.realm_name, "id": flow_id}
  1134. data_raw = self.raw_delete(URL_ADMIN_FLOW.format(**params_path))
  1135. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1136. def get_authentication_flow_executions(self, flow_alias):
  1137. """
  1138. Get authentication flow executions. Returns all execution steps
  1139. :param flow_alias: the flow alias
  1140. :return: Response(json)
  1141. """
  1142. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1143. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1144. return raise_error_from_response(data_raw, KeycloakGetError)
  1145. def update_authentication_flow_executions(self, payload, flow_alias):
  1146. """
  1147. Update an authentication flow execution
  1148. AuthenticationExecutionInfoRepresentation
  1149. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1150. :param payload: AuthenticationExecutionInfoRepresentation
  1151. :param flow_alias: The flow alias
  1152. :return: Keycloak server response
  1153. """
  1154. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1155. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1156. data=json.dumps(payload))
  1157. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1158. def get_authentication_flow_execution(self, execution_id):
  1159. """
  1160. Get authentication flow execution.
  1161. AuthenticationExecutionInfoRepresentation
  1162. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1163. :param execution_id: the execution ID
  1164. :return: Response(json)
  1165. """
  1166. params_path = {"realm-name": self.realm_name, "id": execution_id}
  1167. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTION.format(**params_path))
  1168. return raise_error_from_response(data_raw, KeycloakGetError)
  1169. def create_authentication_flow_execution(self, payload, flow_alias):
  1170. """
  1171. Create an authentication flow execution
  1172. AuthenticationExecutionInfoRepresentation
  1173. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1174. :param payload: AuthenticationExecutionInfoRepresentation
  1175. :param flow_alias: The flow alias
  1176. :return: Keycloak server response
  1177. """
  1178. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1179. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1180. data=json.dumps(payload))
  1181. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1182. def delete_authentication_flow_execution(self, execution_id):
  1183. """
  1184. Delete authentication flow execution
  1185. AuthenticationExecutionInfoRepresentation
  1186. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1187. :param execution_id: keycloak client id (not oauth client-id)
  1188. :return: Keycloak server response (json)
  1189. """
  1190. params_path = {"realm-name": self.realm_name, "id": execution_id}
  1191. data_raw = self.raw_delete(URL_ADMIN_FLOWS_EXECUTION.format(**params_path))
  1192. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1193. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1194. """
  1195. Create a new sub authentication flow for a given authentication flow
  1196. AuthenticationFlowRepresentation
  1197. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1198. :param payload: AuthenticationFlowRepresentation
  1199. :param flow_alias: The flow alias
  1200. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1201. :return: Keycloak server response (RoleRepresentation)
  1202. """
  1203. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1204. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1205. data=json.dumps(payload))
  1206. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1207. def get_authenticator_config(self, config_id):
  1208. """
  1209. Get authenticator configuration. Returns all configuration details.
  1210. :param config_id: Authenticator config id
  1211. :return: Response(json)
  1212. """
  1213. params_path = {"realm-name": self.realm_name, "id": config_id}
  1214. data_raw = self.raw_get(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1215. return raise_error_from_response(data_raw, KeycloakGetError)
  1216. def update_authenticator_config(self, payload, config_id):
  1217. """
  1218. Update an authenticator configuration.
  1219. AuthenticatorConfigRepresentation
  1220. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticatorconfigrepresentation
  1221. :param payload: AuthenticatorConfigRepresentation
  1222. :param config_id: Authenticator config id
  1223. :return: Response(json)
  1224. """
  1225. params_path = {"realm-name": self.realm_name, "id": config_id}
  1226. data_raw = self.raw_put(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1227. data=json.dumps(payload))
  1228. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1229. def delete_authenticator_config(self, config_id):
  1230. """
  1231. Delete a authenticator configuration.
  1232. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource
  1233. :param config_id: Authenticator config id
  1234. :return: Keycloak server Response
  1235. """
  1236. params_path = {"realm-name": self.realm_name, "id": config_id}
  1237. data_raw = self.raw_delete(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1238. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1239. def sync_users(self, storage_id, action):
  1240. """
  1241. Function to trigger user sync from provider
  1242. :param storage_id: The id of the user storage provider
  1243. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1244. :return:
  1245. """
  1246. data = {'action': action}
  1247. params_query = {"action": action}
  1248. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1249. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1250. data=json.dumps(data), **params_query)
  1251. return raise_error_from_response(data_raw, KeycloakGetError)
  1252. def get_client_scopes(self):
  1253. """
  1254. Get representation of the client scopes for the realm where we are connected to
  1255. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1256. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1257. """
  1258. params_path = {"realm-name": self.realm_name}
  1259. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1260. return raise_error_from_response(data_raw, KeycloakGetError)
  1261. def get_client_scope(self, client_scope_id):
  1262. """
  1263. Get representation of the client scopes for the realm where we are connected to
  1264. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1265. :param client_scope_id: The id of the client scope
  1266. :return: Keycloak server response (ClientScopeRepresentation)
  1267. """
  1268. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1269. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1270. return raise_error_from_response(data_raw, KeycloakGetError)
  1271. def create_client_scope(self, payload, skip_exists=False):
  1272. """
  1273. Create a client scope
  1274. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1275. :param payload: ClientScopeRepresentation
  1276. :param skip_exists: If true then do not raise an error if client scope already exists
  1277. :return: Keycloak server response (ClientScopeRepresentation)
  1278. """
  1279. params_path = {"realm-name": self.realm_name}
  1280. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1281. data=json.dumps(payload))
  1282. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1283. def update_client_scope(self, client_scope_id, payload):
  1284. """
  1285. Update a client scope
  1286. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_client_scopes_resource
  1287. :param client_scope_id: The id of the client scope
  1288. :param payload: ClientScopeRepresentation
  1289. :return: Keycloak server response (ClientScopeRepresentation)
  1290. """
  1291. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1292. data_raw = self.raw_put(URL_ADMIN_CLIENT_SCOPE.format(**params_path),
  1293. data=json.dumps(payload))
  1294. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1295. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1296. """
  1297. Add a mapper to a client scope
  1298. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1299. :param client_scope_id: The id of the client scope
  1300. :param payload: ProtocolMapperRepresentation
  1301. :return: Keycloak server Response
  1302. """
  1303. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1304. data_raw = self.raw_post(
  1305. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1306. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1307. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1308. """
  1309. Delete a mapper from a client scope
  1310. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1311. :param client_scope_id: The id of the client scope
  1312. :param payload: ProtocolMapperRepresentation
  1313. :return: Keycloak server Response
  1314. """
  1315. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1316. "protocol-mapper-id": protocol_mppaer_id}
  1317. data_raw = self.raw_delete(
  1318. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1319. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1320. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  1321. """
  1322. Update an existing protocol mapper in a client scope
  1323. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_protocol_mappers_resource
  1324. :param client_scope_id: The id of the client scope
  1325. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  1326. and should to be updated
  1327. :param payload: ProtocolMapperRepresentation
  1328. :return: Keycloak server Response
  1329. """
  1330. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1331. "protocol-mapper-id": protocol_mapper_id}
  1332. data_raw = self.raw_put(
  1333. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path), data=json.dumps(payload))
  1334. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1335. def add_mapper_to_client(self, client_id, payload):
  1336. """
  1337. Add a mapper to a client
  1338. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1339. :param client_id: The id of the client
  1340. :param payload: ProtocolMapperRepresentation
  1341. :return: Keycloak server Response
  1342. """
  1343. params_path = {"realm-name": self.realm_name, "id": client_id}
  1344. data_raw = self.raw_post(
  1345. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1346. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1347. def generate_client_secrets(self, client_id):
  1348. """
  1349. Generate a new secret for the client
  1350. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1351. :param client_id: id of client (not client-id)
  1352. :return: Keycloak server response (ClientRepresentation)
  1353. """
  1354. params_path = {"realm-name": self.realm_name, "id": client_id}
  1355. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1356. return raise_error_from_response(data_raw, KeycloakGetError)
  1357. def get_client_secrets(self, client_id):
  1358. """
  1359. Get representation of the client secrets
  1360. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1361. :param client_id: id of client (not client-id)
  1362. :return: Keycloak server response (ClientRepresentation)
  1363. """
  1364. params_path = {"realm-name": self.realm_name, "id": client_id}
  1365. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1366. return raise_error_from_response(data_raw, KeycloakGetError)
  1367. def get_components(self, query=None):
  1368. """
  1369. Return a list of components, filtered according to query parameters
  1370. ComponentRepresentation
  1371. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1372. :param query: Query parameters (optional)
  1373. :return: components list
  1374. """
  1375. params_path = {"realm-name": self.realm_name}
  1376. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1377. data=None, **query)
  1378. return raise_error_from_response(data_raw, KeycloakGetError)
  1379. def create_component(self, payload):
  1380. """
  1381. Create a new component.
  1382. ComponentRepresentation
  1383. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1384. :param payload: ComponentRepresentation
  1385. :return: UserRepresentation
  1386. """
  1387. params_path = {"realm-name": self.realm_name}
  1388. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1389. data=json.dumps(payload))
  1390. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1391. def get_component(self, component_id):
  1392. """
  1393. Get representation of the component
  1394. :param component_id: Component id
  1395. ComponentRepresentation
  1396. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1397. :return: ComponentRepresentation
  1398. """
  1399. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1400. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1401. return raise_error_from_response(data_raw, KeycloakGetError)
  1402. def update_component(self, component_id, payload):
  1403. """
  1404. Update the component
  1405. :param component_id: Component id
  1406. :param payload: ComponentRepresentation
  1407. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1408. :return: Http response
  1409. """
  1410. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1411. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1412. data=json.dumps(payload))
  1413. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1414. def delete_component(self, component_id):
  1415. """
  1416. Delete the component
  1417. :param component_id: Component id
  1418. :return: Http response
  1419. """
  1420. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1421. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1422. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1423. def get_keys(self):
  1424. """
  1425. Return a list of keys, filtered according to query parameters
  1426. KeysMetadataRepresentation
  1427. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1428. :return: keys list
  1429. """
  1430. params_path = {"realm-name": self.realm_name}
  1431. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1432. data=None)
  1433. return raise_error_from_response(data_raw, KeycloakGetError)
  1434. def get_events(self, query=None):
  1435. """
  1436. Return a list of events, filtered according to query parameters
  1437. EventRepresentation array
  1438. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_eventrepresentation
  1439. :return: events list
  1440. """
  1441. params_path = {"realm-name": self.realm_name}
  1442. data_raw = self.raw_get(URL_ADMIN_EVENTS.format(**params_path),
  1443. data=None, **query)
  1444. return raise_error_from_response(data_raw, KeycloakGetError)
  1445. def set_events(self, payload):
  1446. """
  1447. Set realm events configuration
  1448. RealmEventsConfigRepresentation
  1449. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmeventsconfigrepresentation
  1450. :return: Http response
  1451. """
  1452. params_path = {"realm-name": self.realm_name}
  1453. data_raw = self.raw_put(URL_ADMIN_EVENTS.format(**params_path),
  1454. data=json.dumps(payload))
  1455. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1456. def raw_get(self, *args, **kwargs):
  1457. """
  1458. Calls connection.raw_get.
  1459. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1460. and try *get* once more.
  1461. """
  1462. r = self.connection.raw_get(*args, **kwargs)
  1463. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1464. self.refresh_token()
  1465. return self.connection.raw_get(*args, **kwargs)
  1466. return r
  1467. def raw_post(self, *args, **kwargs):
  1468. """
  1469. Calls connection.raw_post.
  1470. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1471. and try *post* once more.
  1472. """
  1473. r = self.connection.raw_post(*args, **kwargs)
  1474. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1475. self.refresh_token()
  1476. return self.connection.raw_post(*args, **kwargs)
  1477. return r
  1478. def raw_put(self, *args, **kwargs):
  1479. """
  1480. Calls connection.raw_put.
  1481. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1482. and try *put* once more.
  1483. """
  1484. r = self.connection.raw_put(*args, **kwargs)
  1485. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1486. self.refresh_token()
  1487. return self.connection.raw_put(*args, **kwargs)
  1488. return r
  1489. def raw_delete(self, *args, **kwargs):
  1490. """
  1491. Calls connection.raw_delete.
  1492. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1493. and try *delete* once more.
  1494. """
  1495. r = self.connection.raw_delete(*args, **kwargs)
  1496. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1497. self.refresh_token()
  1498. return self.connection.raw_delete(*args, **kwargs)
  1499. return r
  1500. def get_token(self):
  1501. token_realm_name = 'master' if self.client_secret_key else self.user_realm_name or self.realm_name
  1502. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1503. realm_name=token_realm_name, verify=self.verify,
  1504. client_secret_key=self.client_secret_key,
  1505. custom_headers=self.custom_headers)
  1506. grant_type = ["password"]
  1507. if self.client_secret_key:
  1508. grant_type = ["client_credentials"]
  1509. if self.user_realm_name:
  1510. self.realm_name = self.user_realm_name
  1511. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1512. headers = {
  1513. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1514. 'Content-Type': 'application/json'
  1515. }
  1516. if self.custom_headers is not None:
  1517. # merge custom headers to main headers
  1518. headers.update(self.custom_headers)
  1519. self._connection = ConnectionManager(base_url=self.server_url,
  1520. headers=headers,
  1521. timeout=60,
  1522. verify=self.verify)
  1523. def refresh_token(self):
  1524. refresh_token = self.token.get('refresh_token')
  1525. try:
  1526. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1527. except KeycloakGetError as e:
  1528. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1529. b'Token is not active' in e.response_body):
  1530. self.get_token()
  1531. else:
  1532. raise
  1533. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))
  1534. def get_client_all_sessions(self, client_id):
  1535. """
  1536. Get sessions associated with the client
  1537. :param client_id: id of client
  1538. UserSessionRepresentation
  1539. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  1540. :return: UserSessionRepresentation
  1541. """
  1542. params_path = {"realm-name": self.realm_name, "id": client_id}
  1543. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  1544. return raise_error_from_response(data_raw, KeycloakGetError)
  1545. def delete_user_realm_role(self, user_id, payload):
  1546. """
  1547. Delete realm-level role mappings
  1548. DELETE admin/realms/{realm-name}/users/{id}/role-mappings/realm
  1549. """
  1550. params_path = {"realm-name": self.realm_name, "id": str(user_id) }
  1551. data_raw = self.connection.raw_delete(URL_ADMIN_DELETE_USER_ROLE.format(**params_path),
  1552. data=json.dumps(payload))
  1553. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])