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.

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