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.

2026 lines
80 KiB

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