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.

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