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.

1755 lines
68 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
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
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
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
  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=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=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=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=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=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=payload)
  1130. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1131. def sync_users(self, storage_id, action):
  1132. """
  1133. Function to trigger user sync from provider
  1134. :param storage_id: The id of the user storage provider
  1135. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1136. :return:
  1137. """
  1138. data = {'action': action}
  1139. params_query = {"action": action}
  1140. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1141. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1142. data=json.dumps(data), **params_query)
  1143. return raise_error_from_response(data_raw, KeycloakGetError)
  1144. def get_client_scopes(self):
  1145. """
  1146. Get representation of the client scopes for the realm where we are connected to
  1147. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1148. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1149. """
  1150. params_path = {"realm-name": self.realm_name}
  1151. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1152. return raise_error_from_response(data_raw, KeycloakGetError)
  1153. def get_client_scope(self, client_scope_id):
  1154. """
  1155. Get representation of the client scopes for the realm where we are connected to
  1156. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1157. :param client_scope_id: The id of the client scope
  1158. :return: Keycloak server response (ClientScopeRepresentation)
  1159. """
  1160. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1161. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1162. return raise_error_from_response(data_raw, KeycloakGetError)
  1163. def create_client_scope(self, payload, skip_exists=False):
  1164. """
  1165. Create a client scope
  1166. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1167. :param payload: ClientScopeRepresentation
  1168. :param skip_exists: If true then do not raise an error if client scope already exists
  1169. :return: Keycloak server response (ClientScopeRepresentation)
  1170. """
  1171. params_path = {"realm-name": self.realm_name}
  1172. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1173. data=json.dumps(payload))
  1174. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1175. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1176. """
  1177. Add a mapper to a client scope
  1178. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1179. :param client_scope_id: The id of the client scope
  1180. :param payload: ProtocolMapperRepresentation
  1181. :return: Keycloak server Response
  1182. """
  1183. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1184. data_raw = self.raw_post(
  1185. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1186. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1187. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1188. """
  1189. Delete a mapper from a client scope
  1190. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1191. :param client_scope_id: The id of the client scope
  1192. :param payload: ProtocolMapperRepresentation
  1193. :return: Keycloak server Response
  1194. """
  1195. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1196. "protocol-mapper-id": protocol_mppaer_id}
  1197. data_raw = self.raw_delete(
  1198. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1199. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1200. def add_mapper_to_client(self, client_id, payload):
  1201. """
  1202. Add a mapper to a client
  1203. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1204. :param client_id: The id of the client
  1205. :param payload: ProtocolMapperRepresentation
  1206. :return: Keycloak server Response
  1207. """
  1208. params_path = {"realm-name": self.realm_name, "id": client_id}
  1209. data_raw = self.raw_post(
  1210. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1211. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1212. def generate_client_secrets(self, client_id):
  1213. """
  1214. Generate a new secret for the client
  1215. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1216. :param client_id: id of client (not client-id)
  1217. :return: Keycloak server response (ClientRepresentation)
  1218. """
  1219. params_path = {"realm-name": self.realm_name, "id": client_id}
  1220. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1221. return raise_error_from_response(data_raw, KeycloakGetError)
  1222. def get_client_secrets(self, client_id):
  1223. """
  1224. Get representation of the client secrets
  1225. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1226. :param client_id: id of client (not client-id)
  1227. :return: Keycloak server response (ClientRepresentation)
  1228. """
  1229. params_path = {"realm-name": self.realm_name, "id": client_id}
  1230. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1231. return raise_error_from_response(data_raw, KeycloakGetError)
  1232. def get_components(self, query=None):
  1233. """
  1234. Return a list of components, filtered according to query parameters
  1235. ComponentRepresentation
  1236. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1237. :param query: Query parameters (optional)
  1238. :return: components list
  1239. """
  1240. params_path = {"realm-name": self.realm_name}
  1241. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1242. data=None, **query)
  1243. return raise_error_from_response(data_raw, KeycloakGetError)
  1244. def create_component(self, payload):
  1245. """
  1246. Create a new component.
  1247. ComponentRepresentation
  1248. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1249. :param payload: ComponentRepresentation
  1250. :return: UserRepresentation
  1251. """
  1252. params_path = {"realm-name": self.realm_name}
  1253. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1254. data=json.dumps(payload))
  1255. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1256. def get_component(self, component_id):
  1257. """
  1258. Get representation of the component
  1259. :param component_id: Component id
  1260. ComponentRepresentation
  1261. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1262. :return: ComponentRepresentation
  1263. """
  1264. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1265. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1266. return raise_error_from_response(data_raw, KeycloakGetError)
  1267. def update_component(self, component_id, payload):
  1268. """
  1269. Update the component
  1270. :param component_id: Component id
  1271. :param payload: ComponentRepresentation
  1272. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1273. :return: Http response
  1274. """
  1275. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1276. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1277. data=json.dumps(payload))
  1278. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1279. def delete_component(self, component_id):
  1280. """
  1281. Delete the component
  1282. :param component_id: Component id
  1283. :return: Http response
  1284. """
  1285. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1286. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1287. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1288. def get_keys(self):
  1289. """
  1290. Return a list of keys, filtered according to query parameters
  1291. KeysMetadataRepresentation
  1292. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1293. :return: keys list
  1294. """
  1295. params_path = {"realm-name": self.realm_name}
  1296. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1297. data=None)
  1298. return raise_error_from_response(data_raw, KeycloakGetError)
  1299. def raw_get(self, *args, **kwargs):
  1300. """
  1301. Calls connection.raw_get.
  1302. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1303. and try *get* once more.
  1304. """
  1305. r = self.connection.raw_get(*args, **kwargs)
  1306. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1307. self.refresh_token()
  1308. return self.connection.raw_get(*args, **kwargs)
  1309. return r
  1310. def raw_post(self, *args, **kwargs):
  1311. """
  1312. Calls connection.raw_post.
  1313. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1314. and try *post* once more.
  1315. """
  1316. r = self.connection.raw_post(*args, **kwargs)
  1317. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1318. self.refresh_token()
  1319. return self.connection.raw_post(*args, **kwargs)
  1320. return r
  1321. def raw_put(self, *args, **kwargs):
  1322. """
  1323. Calls connection.raw_put.
  1324. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1325. and try *put* once more.
  1326. """
  1327. r = self.connection.raw_put(*args, **kwargs)
  1328. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1329. self.refresh_token()
  1330. return self.connection.raw_put(*args, **kwargs)
  1331. return r
  1332. def raw_delete(self, *args, **kwargs):
  1333. """
  1334. Calls connection.raw_delete.
  1335. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1336. and try *delete* once more.
  1337. """
  1338. r = self.connection.raw_delete(*args, **kwargs)
  1339. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1340. self.refresh_token()
  1341. return self.connection.raw_delete(*args, **kwargs)
  1342. return r
  1343. def get_token(self):
  1344. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1345. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1346. client_secret_key=self.client_secret_key,
  1347. custom_headers=self.custom_headers)
  1348. grant_type = ["password"]
  1349. if self.client_secret_key:
  1350. grant_type = ["client_credentials"]
  1351. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1352. headers = {
  1353. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1354. 'Content-Type': 'application/json'
  1355. }
  1356. if self.custom_headers is not None:
  1357. # merge custom headers to main headers
  1358. headers.update(self.custom_headers)
  1359. self._connection = ConnectionManager(base_url=self.server_url,
  1360. headers=headers,
  1361. timeout=60,
  1362. verify=self.verify)
  1363. def refresh_token(self):
  1364. refresh_token = self.token.get('refresh_token')
  1365. try:
  1366. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1367. except KeycloakGetError as e:
  1368. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1369. b'Token is not active' in e.response_body):
  1370. self.get_token()
  1371. else:
  1372. raise
  1373. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))