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.

1952 lines
77 KiB

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