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.

1758 lines
69 KiB

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