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.

1754 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
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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, roles):
  906. """
  907. Assign realm roles to a user
  908. :param user_id: id of user
  909. :param roles: roles list or role (use RoleRepresentation)
  910. :return Keycloak server response
  911. """
  912. payload = roles if isinstance(roles, list) else [roles]
  913. params_path = {"realm-name": self.realm_name, "id": user_id}
  914. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  915. data=json.dumps(payload))
  916. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  917. def get_realm_roles_of_user(self, user_id):
  918. """
  919. Get all realm roles for a user.
  920. :param user_id: id of user
  921. :return: Keycloak server response (array RoleRepresentation)
  922. """
  923. params_path = {"realm-name": self.realm_name, "id": user_id}
  924. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  925. return raise_error_from_response(data_raw, KeycloakGetError)
  926. def assign_group_realm_roles(self, group_id, roles):
  927. """
  928. Assign realm roles to a group
  929. :param group_id: id of groupp
  930. :param roles: roles list or role (use GroupRoleRepresentation)
  931. :return Keycloak server response
  932. """
  933. payload = roles if isinstance(roles, list) else [roles]
  934. params_path = {"realm-name": self.realm_name, "id": group_id}
  935. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  936. data=json.dumps(payload))
  937. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  938. def delete_group_realm_roles(self, group_id, roles):
  939. """
  940. Delete realm roles of a group
  941. :param group_id: id of group
  942. :param roles: roles list or role (use GroupRoleRepresentation)
  943. :return Keycloak server response
  944. """
  945. payload = roles if isinstance(roles, list) else [roles]
  946. params_path = {"realm-name": self.realm_name, "id": group_id}
  947. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  948. data=json.dumps(payload))
  949. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  950. def get_group_realm_roles(self, group_id):
  951. """
  952. Get all realm roles for a group.
  953. :param user_id: id of the group
  954. :return: Keycloak server response (array RoleRepresentation)
  955. """
  956. params_path = {"realm-name": self.realm_name, "id": group_id}
  957. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  958. return raise_error_from_response(data_raw, KeycloakGetError)
  959. def assign_group_client_roles(self, group_id, client_id, roles):
  960. """
  961. Assign client roles to a group
  962. :param group_id: id of group
  963. :param client_id: id of client (not client-id)
  964. :param roles: roles list or role (use GroupRoleRepresentation)
  965. :return Keycloak server response
  966. """
  967. payload = roles if isinstance(roles, list) else [roles]
  968. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  969. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  970. data=json.dumps(payload))
  971. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  972. def get_group_client_roles(self, group_id, client_id):
  973. """
  974. Get client roles of a group
  975. :param group_id: id of group
  976. :param client_id: id of client (not client-id)
  977. :return Keycloak server response
  978. """
  979. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  980. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  981. return raise_error_from_response(data_raw, KeycloakGetError)
  982. def delete_group_client_roles(self, group_id, client_id, roles):
  983. """
  984. Delete client roles of a group
  985. :param group_id: id of group
  986. :param client_id: id of client (not client-id)
  987. :param roles: roles list or role (use GroupRoleRepresentation)
  988. :return Keycloak server response (array RoleRepresentation)
  989. """
  990. payload = roles if isinstance(roles, list) else [roles]
  991. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  992. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  993. data=json.dumps(payload))
  994. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  995. def get_client_roles_of_user(self, user_id, client_id):
  996. """
  997. Get all client roles for a user.
  998. :param user_id: id of user
  999. :param client_id: id of client (not client-id)
  1000. :return: Keycloak server response (array RoleRepresentation)
  1001. """
  1002. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1003. def get_available_client_roles_of_user(self, user_id, client_id):
  1004. """
  1005. Get available client role-mappings for a user.
  1006. :param user_id: id of user
  1007. :param client_id: id of client (not client-id)
  1008. :return: Keycloak server response (array RoleRepresentation)
  1009. """
  1010. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1011. def get_composite_client_roles_of_user(self, user_id, client_id):
  1012. """
  1013. Get composite client role-mappings for a user.
  1014. :param user_id: id of user
  1015. :param client_id: id of client (not client-id)
  1016. :return: Keycloak server response (array RoleRepresentation)
  1017. """
  1018. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1019. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1020. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1021. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1022. return raise_error_from_response(data_raw, KeycloakGetError)
  1023. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1024. """
  1025. Delete client roles from a user.
  1026. :param user_id: id of user
  1027. :param client_id: id of client containing role (not client-id)
  1028. :param roles: roles list or role to delete (use RoleRepresentation)
  1029. :return: Keycloak server response
  1030. """
  1031. payload = roles if isinstance(roles, list) else [roles]
  1032. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1033. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1034. data=json.dumps(payload))
  1035. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1036. def get_authentication_flows(self):
  1037. """
  1038. Get authentication flows. Returns all flow details
  1039. AuthenticationFlowRepresentation
  1040. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1041. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1042. """
  1043. params_path = {"realm-name": self.realm_name}
  1044. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1045. return raise_error_from_response(data_raw, KeycloakGetError)
  1046. def get_authentication_flow_for_id(self, flow_id):
  1047. """
  1048. Get one authentication flow by it's id/alias. Returns all flow details
  1049. AuthenticationFlowRepresentation
  1050. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1051. :param flow_id: the id of a flow NOT it's alias
  1052. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1053. """
  1054. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1055. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1056. return raise_error_from_response(data_raw, KeycloakGetError)
  1057. def create_authentication_flow(self, payload, skip_exists=False):
  1058. """
  1059. Create a new authentication flow
  1060. AuthenticationFlowRepresentation
  1061. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1062. :param payload: AuthenticationFlowRepresentation
  1063. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1064. :return: Keycloak server response (RoleRepresentation)
  1065. """
  1066. params_path = {"realm-name": self.realm_name}
  1067. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1068. data=payload)
  1069. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1070. def copy_authentication_flow(self, payload, flow_alias):
  1071. """
  1072. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1073. :param payload: JSON containing 'newName' attribute
  1074. :param flow_alias: the flow alias
  1075. :return: Keycloak server response (RoleRepresentation)
  1076. """
  1077. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1078. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1079. data=payload)
  1080. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1081. def get_authentication_flow_executions(self, flow_alias):
  1082. """
  1083. Get authentication flow executions. Returns all execution steps
  1084. :param flow_alias: the flow alias
  1085. :return: Response(json)
  1086. """
  1087. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1088. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1089. return raise_error_from_response(data_raw, KeycloakGetError)
  1090. def update_authentication_flow_executions(self, payload, flow_alias):
  1091. """
  1092. Update an authentication flow execution
  1093. AuthenticationExecutionInfoRepresentation
  1094. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1095. :param payload: AuthenticationExecutionInfoRepresentation
  1096. :param flow_alias: The flow alias
  1097. :return: Keycloak server response
  1098. """
  1099. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1100. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1101. data=payload)
  1102. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1103. def create_authentication_flow_execution(self, payload, flow_alias):
  1104. """
  1105. Create an authentication flow execution
  1106. AuthenticationExecutionInfoRepresentation
  1107. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1108. :param payload: AuthenticationExecutionInfoRepresentation
  1109. :param flow_alias: The flow alias
  1110. :return: Keycloak server response
  1111. """
  1112. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1113. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1114. data=payload)
  1115. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1116. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1117. """
  1118. Create a new sub authentication flow for a given authentication flow
  1119. AuthenticationFlowRepresentation
  1120. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1121. :param payload: AuthenticationFlowRepresentation
  1122. :param flow_alias: The flow alias
  1123. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1124. :return: Keycloak server response (RoleRepresentation)
  1125. """
  1126. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1127. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1128. data=payload)
  1129. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1130. def sync_users(self, storage_id, action):
  1131. """
  1132. Function to trigger user sync from provider
  1133. :param storage_id: The id of the user storage provider
  1134. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1135. :return:
  1136. """
  1137. data = {'action': action}
  1138. params_query = {"action": action}
  1139. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1140. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1141. data=json.dumps(data), **params_query)
  1142. return raise_error_from_response(data_raw, KeycloakGetError)
  1143. def get_client_scopes(self):
  1144. """
  1145. Get representation of the client scopes for the realm where we are connected to
  1146. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1147. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1148. """
  1149. params_path = {"realm-name": self.realm_name}
  1150. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1151. return raise_error_from_response(data_raw, KeycloakGetError)
  1152. def get_client_scope(self, client_scope_id):
  1153. """
  1154. Get representation of the client scopes for the realm where we are connected to
  1155. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1156. :param client_scope_id: The id of the client scope
  1157. :return: Keycloak server response (ClientScopeRepresentation)
  1158. """
  1159. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1160. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1161. return raise_error_from_response(data_raw, KeycloakGetError)
  1162. def create_client_scope(self, payload, skip_exists=False):
  1163. """
  1164. Create a client scope
  1165. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1166. :param payload: ClientScopeRepresentation
  1167. :param skip_exists: If true then do not raise an error if client scope already exists
  1168. :return: Keycloak server response (ClientScopeRepresentation)
  1169. """
  1170. params_path = {"realm-name": self.realm_name}
  1171. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1172. data=json.dumps(payload))
  1173. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1174. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1175. """
  1176. Add a mapper to a client scope
  1177. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1178. :param client_scope_id: The id of the client scope
  1179. :param payload: ProtocolMapperRepresentation
  1180. :return: Keycloak server Response
  1181. """
  1182. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1183. data_raw = self.raw_post(
  1184. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1185. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1186. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1187. """
  1188. Delete a mapper from a client scope
  1189. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1190. :param client_scope_id: The id of the client scope
  1191. :param payload: ProtocolMapperRepresentation
  1192. :return: Keycloak server Response
  1193. """
  1194. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1195. "protocol-mapper-id": protocol_mppaer_id}
  1196. data_raw = self.raw_delete(
  1197. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1198. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1199. def add_mapper_to_client(self, client_id, payload):
  1200. """
  1201. Add a mapper to a client
  1202. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1203. :param client_id: The id of the client
  1204. :param payload: ProtocolMapperRepresentation
  1205. :return: Keycloak server Response
  1206. """
  1207. params_path = {"realm-name": self.realm_name, "id": client_id}
  1208. data_raw = self.raw_post(
  1209. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1210. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1211. def generate_client_secrets(self, client_id):
  1212. """
  1213. Generate a new secret for the client
  1214. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1215. :param client_id: id of client (not client-id)
  1216. :return: Keycloak server response (ClientRepresentation)
  1217. """
  1218. params_path = {"realm-name": self.realm_name, "id": client_id}
  1219. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1220. return raise_error_from_response(data_raw, KeycloakGetError)
  1221. def get_client_secrets(self, client_id):
  1222. """
  1223. Get representation of the client secrets
  1224. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1225. :param client_id: id of client (not client-id)
  1226. :return: Keycloak server response (ClientRepresentation)
  1227. """
  1228. params_path = {"realm-name": self.realm_name, "id": client_id}
  1229. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1230. return raise_error_from_response(data_raw, KeycloakGetError)
  1231. def get_components(self, query=None):
  1232. """
  1233. Return a list of components, filtered according to query parameters
  1234. ComponentRepresentation
  1235. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1236. :param query: Query parameters (optional)
  1237. :return: components list
  1238. """
  1239. params_path = {"realm-name": self.realm_name}
  1240. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1241. data=None, **query)
  1242. return raise_error_from_response(data_raw, KeycloakGetError)
  1243. def create_component(self, payload):
  1244. """
  1245. Create a new component.
  1246. ComponentRepresentation
  1247. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1248. :param payload: ComponentRepresentation
  1249. :return: UserRepresentation
  1250. """
  1251. params_path = {"realm-name": self.realm_name}
  1252. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1253. data=json.dumps(payload))
  1254. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1255. def get_component(self, component_id):
  1256. """
  1257. Get representation of the component
  1258. :param component_id: Component id
  1259. ComponentRepresentation
  1260. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1261. :return: ComponentRepresentation
  1262. """
  1263. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1264. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1265. return raise_error_from_response(data_raw, KeycloakGetError)
  1266. def update_component(self, component_id, payload):
  1267. """
  1268. Update the component
  1269. :param component_id: Component id
  1270. :param payload: ComponentRepresentation
  1271. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1272. :return: Http response
  1273. """
  1274. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1275. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1276. data=json.dumps(payload))
  1277. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1278. def delete_component(self, component_id):
  1279. """
  1280. Delete the component
  1281. :param component_id: Component id
  1282. :return: Http response
  1283. """
  1284. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1285. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1286. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1287. def get_keys(self):
  1288. """
  1289. Return a list of keys, filtered according to query parameters
  1290. KeysMetadataRepresentation
  1291. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1292. :return: keys list
  1293. """
  1294. params_path = {"realm-name": self.realm_name}
  1295. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1296. data=None)
  1297. return raise_error_from_response(data_raw, KeycloakGetError)
  1298. def raw_get(self, *args, **kwargs):
  1299. """
  1300. Calls connection.raw_get.
  1301. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1302. and try *get* once more.
  1303. """
  1304. r = self.connection.raw_get(*args, **kwargs)
  1305. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1306. self.refresh_token()
  1307. return self.connection.raw_get(*args, **kwargs)
  1308. return r
  1309. def raw_post(self, *args, **kwargs):
  1310. """
  1311. Calls connection.raw_post.
  1312. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1313. and try *post* once more.
  1314. """
  1315. r = self.connection.raw_post(*args, **kwargs)
  1316. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1317. self.refresh_token()
  1318. return self.connection.raw_post(*args, **kwargs)
  1319. return r
  1320. def raw_put(self, *args, **kwargs):
  1321. """
  1322. Calls connection.raw_put.
  1323. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1324. and try *put* once more.
  1325. """
  1326. r = self.connection.raw_put(*args, **kwargs)
  1327. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1328. self.refresh_token()
  1329. return self.connection.raw_put(*args, **kwargs)
  1330. return r
  1331. def raw_delete(self, *args, **kwargs):
  1332. """
  1333. Calls connection.raw_delete.
  1334. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1335. and try *delete* once more.
  1336. """
  1337. r = self.connection.raw_delete(*args, **kwargs)
  1338. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1339. self.refresh_token()
  1340. return self.connection.raw_delete(*args, **kwargs)
  1341. return r
  1342. def get_token(self):
  1343. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1344. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1345. client_secret_key=self.client_secret_key,
  1346. custom_headers=self.custom_headers)
  1347. grant_type = ["password"]
  1348. if self.client_secret_key:
  1349. grant_type = ["client_credentials"]
  1350. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1351. headers = {
  1352. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1353. 'Content-Type': 'application/json'
  1354. }
  1355. if self.custom_headers is not None:
  1356. # merge custom headers to main headers
  1357. headers.update(self.custom_headers)
  1358. self._connection = ConnectionManager(base_url=self.server_url,
  1359. headers=headers,
  1360. timeout=60,
  1361. verify=self.verify)
  1362. def refresh_token(self):
  1363. refresh_token = self.token.get('refresh_token')
  1364. try:
  1365. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1366. except KeycloakGetError as e:
  1367. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1368. b'Token is not active' in e.response_body):
  1369. self.get_token()
  1370. else:
  1371. raise
  1372. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))