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.

1689 lines
65 KiB

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