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.

1206 lines
45 KiB

7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 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
6 years ago
7 years ago
7 years ago
7 years ago
7 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
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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 .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, \
  33. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  34. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  35. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  36. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  37. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, \
  38. URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  39. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  40. URL_ADMIN_USER_REALM_ROLES
  41. class KeycloakAdmin:
  42. PAGE_SIZE = 100
  43. _server_url = None
  44. _username = None
  45. _password = None
  46. _realm_name = None
  47. _client_id = None
  48. _verify = None
  49. _client_secret_key = None
  50. _auto_refresh_token = None
  51. _connection = None
  52. _token = None
  53. _custom_headers = None
  54. _user_realm_name = None
  55. def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli', verify=True,
  56. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  57. """
  58. :param server_url: Keycloak server url
  59. :param username: admin username
  60. :param password: admin password
  61. :param realm_name: realm name
  62. :param client_id: client id
  63. :param verify: True if want check connection SSL
  64. :param client_secret_key: client secret key
  65. :param custom_headers: dict of custom header to pass to each HTML request
  66. :param user_realm_name: The realm name of the user, if different from realm_name
  67. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  68. """
  69. self.server_url = server_url
  70. self.username = username
  71. self.password = password
  72. self.realm_name = realm_name
  73. self.client_id = client_id
  74. self.verify = verify
  75. self.client_secret_key = client_secret_key
  76. self.auto_refresh_token = auto_refresh_token or []
  77. self.user_realm_name = user_realm_name
  78. self.custom_headers = custom_headers
  79. # Get token Admin
  80. self.get_token()
  81. @property
  82. def server_url(self):
  83. return self._server_url
  84. @server_url.setter
  85. def server_url(self, value):
  86. self._server_url = value
  87. @property
  88. def realm_name(self):
  89. return self._realm_name
  90. @realm_name.setter
  91. def realm_name(self, value):
  92. self._realm_name = value
  93. @property
  94. def connection(self):
  95. return self._connection
  96. @connection.setter
  97. def connection(self, value):
  98. self._connection = value
  99. @property
  100. def client_id(self):
  101. return self._client_id
  102. @client_id.setter
  103. def client_id(self, value):
  104. self._client_id = value
  105. @property
  106. def client_secret_key(self):
  107. return self._client_secret_key
  108. @client_secret_key.setter
  109. def client_secret_key(self, value):
  110. self._client_secret_key = value
  111. @property
  112. def verify(self):
  113. return self._verify
  114. @verify.setter
  115. def verify(self, value):
  116. self._verify = value
  117. @property
  118. def username(self):
  119. return self._username
  120. @username.setter
  121. def username(self, value):
  122. self._username = value
  123. @property
  124. def password(self):
  125. return self._password
  126. @password.setter
  127. def password(self, value):
  128. self._password = value
  129. @property
  130. def token(self):
  131. return self._token
  132. @token.setter
  133. def token(self, value):
  134. self._token = value
  135. @property
  136. def auto_refresh_token(self):
  137. return self._auto_refresh_token
  138. @property
  139. def user_realm_name(self):
  140. return self._user_realm_name
  141. @user_realm_name.setter
  142. def user_realm_name(self, value):
  143. self._user_realm_name = value
  144. @property
  145. def custom_headers(self):
  146. return self._custom_headers
  147. @custom_headers.setter
  148. def custom_headers(self, value):
  149. self._custom_headers = value
  150. @auto_refresh_token.setter
  151. def auto_refresh_token(self, value):
  152. allowed_methods = {'get', 'post', 'put', 'delete'}
  153. if not isinstance(value, Iterable):
  154. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  155. if not all(method in allowed_methods for method in value):
  156. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  157. self._auto_refresh_token = value
  158. def __fetch_all(self, url, query=None):
  159. '''Wrapper function to paginate GET requests
  160. :param url: The url on which the query is executed
  161. :param query: Existing query parameters (optional)
  162. :return: Combined results of paginated queries
  163. '''
  164. results = []
  165. # initalize query if it was called with None
  166. if not query:
  167. query = {}
  168. page = 0
  169. query['max'] = self.PAGE_SIZE
  170. # fetch until we can
  171. while True:
  172. query['first'] = page*self.PAGE_SIZE
  173. partial_results = raise_error_from_response(
  174. self.raw_get(url, **query),
  175. KeycloakGetError)
  176. if not partial_results:
  177. break
  178. results.extend(partial_results)
  179. page += 1
  180. return results
  181. def import_realm(self, payload):
  182. """
  183. Import a new realm from a RealmRepresentation. Realm name must be unique.
  184. RealmRepresentation
  185. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  186. :param payload: RealmRepresentation
  187. :return: RealmRepresentation
  188. """
  189. data_raw = self.raw_post(URL_ADMIN_REALMS,
  190. data=json.dumps(payload))
  191. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  192. def get_realms(self):
  193. """
  194. Lists all realms in Keycloak deployment
  195. :return: realms list
  196. """
  197. data_raw = self.raw_get(URL_ADMIN_REALMS)
  198. return raise_error_from_response(data_raw, KeycloakGetError)
  199. def create_realm(self, payload, skip_exists=False):
  200. """
  201. Create a realm
  202. RealmRepresentation:
  203. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  204. :param payload: RealmRepresentation
  205. :param skip_exists: Skip if Realm already exist.
  206. :return: Keycloak server response (RealmRepresentation)
  207. """
  208. data_raw = self.raw_post(URL_ADMIN_REALMS,
  209. data=json.dumps(payload))
  210. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  211. def get_users(self, query=None):
  212. """
  213. Return a list of users, filtered according to query parameters
  214. UserRepresentation
  215. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  216. :param query: Query parameters (optional)
  217. :return: users list
  218. """
  219. params_path = {"realm-name": self.realm_name}
  220. return self.__fetch_all(URL_ADMIN_USERS.format(**params_path), query)
  221. def get_idps(self):
  222. """
  223. Returns a list of ID Providers,
  224. IdentityProviderRepresentation
  225. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  226. :return: array IdentityProviderRepresentation
  227. """
  228. params_path = {"realm-name": self.realm_name}
  229. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  230. return raise_error_from_response(data_raw, KeycloakGetError)
  231. def create_user(self, payload):
  232. """
  233. Create a new user. Username must be unique
  234. UserRepresentation
  235. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  236. :param payload: UserRepresentation
  237. :return: UserRepresentation
  238. """
  239. params_path = {"realm-name": self.realm_name}
  240. exists = self.get_user_id(username=payload['username'])
  241. if exists is not None:
  242. return str(exists)
  243. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  244. data=json.dumps(payload))
  245. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  246. def users_count(self):
  247. """
  248. User counter
  249. :return: counter
  250. """
  251. params_path = {"realm-name": self.realm_name}
  252. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  253. return raise_error_from_response(data_raw, KeycloakGetError)
  254. def get_user_id(self, username):
  255. """
  256. Get internal keycloak user id from username
  257. This is required for further actions against this user.
  258. UserRepresentation
  259. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  260. :param username: id in UserRepresentation
  261. :return: user_id
  262. """
  263. users = self.get_users(query={"search": username})
  264. return next((user["id"] for user in users if user["username"] == username), None)
  265. def get_user(self, user_id):
  266. """
  267. Get representation of the user
  268. :param user_id: User id
  269. UserRepresentation
  270. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  271. :return: UserRepresentation
  272. """
  273. params_path = {"realm-name": self.realm_name, "id": user_id}
  274. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  275. return raise_error_from_response(data_raw, KeycloakGetError)
  276. def get_user_groups(self, user_id):
  277. """
  278. Returns a list of groups of which the user is a member
  279. :param user_id: User id
  280. :return: user groups list
  281. """
  282. params_path = {"realm-name": self.realm_name, "id": user_id}
  283. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  284. return raise_error_from_response(data_raw, KeycloakGetError)
  285. def update_user(self, user_id, payload):
  286. """
  287. Update the user
  288. :param user_id: User id
  289. :param payload: UserRepresentation
  290. :return: Http response
  291. """
  292. params_path = {"realm-name": self.realm_name, "id": user_id}
  293. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  294. data=json.dumps(payload))
  295. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  296. def delete_user(self, user_id):
  297. """
  298. Delete the user
  299. :param user_id: User id
  300. :return: Http response
  301. """
  302. params_path = {"realm-name": self.realm_name, "id": user_id}
  303. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  304. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  305. def set_user_password(self, user_id, password, temporary=True):
  306. """
  307. Set up a password for the user. If temporary is True, the user will have to reset
  308. the temporary password next time they log in.
  309. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  310. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  311. :param user_id: User id
  312. :param password: New password
  313. :param temporary: True if password is temporary
  314. :return:
  315. """
  316. payload = {"type": "password", "temporary": temporary, "value": password}
  317. params_path = {"realm-name": self.realm_name, "id": user_id}
  318. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  319. data=json.dumps(payload))
  320. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  321. def consents_user(self, user_id):
  322. """
  323. Get consents granted by the user
  324. :param user_id: User id
  325. :return: consents
  326. """
  327. params_path = {"realm-name": self.realm_name, "id": user_id}
  328. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  329. return raise_error_from_response(data_raw, KeycloakGetError)
  330. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  331. """
  332. Send an update account email to the user. An email contains a
  333. link the user can click to perform a set of required actions.
  334. :param user_id: User id
  335. :param payload: A list of actions for the user to complete
  336. :param client_id: Client id (optional)
  337. :param lifespan: Number of seconds after which the generated token expires (optional)
  338. :param redirect_uri: The redirect uri (optional)
  339. :return:
  340. """
  341. params_path = {"realm-name": self.realm_name, "id": user_id}
  342. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  343. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  344. data=payload, **params_query)
  345. return raise_error_from_response(data_raw, KeycloakGetError)
  346. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  347. """
  348. Send a update account email to the user An email contains a
  349. link the user can click to perform a set of required actions.
  350. :param user_id: User id
  351. :param client_id: Client id (optional)
  352. :param redirect_uri: Redirect uri (optional)
  353. :return:
  354. """
  355. params_path = {"realm-name": self.realm_name, "id": user_id}
  356. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  357. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  358. data={}, **params_query)
  359. return raise_error_from_response(data_raw, KeycloakGetError)
  360. def get_sessions(self, user_id):
  361. """
  362. Get sessions associated with the user
  363. :param user_id: id of user
  364. UserSessionRepresentation
  365. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  366. :return: UserSessionRepresentation
  367. """
  368. params_path = {"realm-name": self.realm_name, "id": user_id}
  369. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  370. return raise_error_from_response(data_raw, KeycloakGetError)
  371. def get_server_info(self):
  372. """
  373. Get themes, social providers, auth providers, and event listeners available on this server
  374. ServerInfoRepresentation
  375. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  376. :return: ServerInfoRepresentation
  377. """
  378. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  379. return raise_error_from_response(data_raw, KeycloakGetError)
  380. def get_groups(self):
  381. """
  382. Returns a list of groups belonging to the realm
  383. GroupRepresentation
  384. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  385. :return: array GroupRepresentation
  386. """
  387. params_path = {"realm-name": self.realm_name}
  388. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  389. def get_group(self, group_id):
  390. """
  391. Get group by id. Returns full group details
  392. GroupRepresentation
  393. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  394. :param group_id: The group id
  395. :return: Keycloak server response (GroupRepresentation)
  396. """
  397. params_path = {"realm-name": self.realm_name, "id": group_id}
  398. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  399. return raise_error_from_response(data_raw, KeycloakGetError)
  400. def get_subgroups(self, group, path):
  401. """
  402. Utility function to iterate through nested group structures
  403. GroupRepresentation
  404. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  405. :param name: group (GroupRepresentation)
  406. :param path: group path (string)
  407. :return: Keycloak server response (GroupRepresentation)
  408. """
  409. for subgroup in group["subGroups"]:
  410. if subgroup['path'] == path:
  411. return subgroup
  412. elif subgroup["subGroups"]:
  413. for subgroup in group["subGroups"]:
  414. result = self.get_subgroups(subgroup, path)
  415. if result:
  416. return result
  417. # went through the tree without hits
  418. return None
  419. def get_group_members(self, group_id, **query):
  420. """
  421. Get members by group id. Returns group members
  422. GroupRepresentation
  423. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  424. :param group_id: The group id
  425. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  426. :return: Keycloak server response (UserRepresentation)
  427. """
  428. params_path = {"realm-name": self.realm_name, "id": group_id}
  429. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  430. def get_group_by_path(self, path, search_in_subgroups=False):
  431. """
  432. Get group id based on name or path.
  433. A straight name or path match with a top-level group will return first.
  434. Subgroups are traversed, the first to match path (or name with path) is returned.
  435. GroupRepresentation
  436. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  437. :param path: group path
  438. :param search_in_subgroups: True if want search in the subgroups
  439. :return: Keycloak server response (GroupRepresentation)
  440. """
  441. groups = self.get_groups()
  442. # TODO: Review this code is necessary
  443. for group in groups:
  444. if group['path'] == path:
  445. return group
  446. elif search_in_subgroups and group["subGroups"]:
  447. for group in group["subGroups"]:
  448. if group['path'] == path:
  449. return group
  450. res = self.get_subgroups(group, path)
  451. if res != None:
  452. return res
  453. return None
  454. def create_group(self, payload, parent=None, skip_exists=False):
  455. """
  456. Creates a group in the Realm
  457. :param payload: GroupRepresentation
  458. :param parent: parent group's id. Required to create a sub-group.
  459. :param skip_exists: If true then do not raise an error if it already exists
  460. GroupRepresentation
  461. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  462. :return: Http response
  463. """
  464. if parent is None:
  465. params_path = {"realm-name": self.realm_name}
  466. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  467. data=json.dumps(payload))
  468. else:
  469. params_path = {"realm-name": self.realm_name, "id": parent, }
  470. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  471. data=json.dumps(payload))
  472. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  473. def update_group(self, group_id, payload):
  474. """
  475. Update group, ignores subgroups.
  476. :param group_id: id of group
  477. :param payload: GroupRepresentation with updated information.
  478. GroupRepresentation
  479. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  480. :return: Http response
  481. """
  482. params_path = {"realm-name": self.realm_name, "id": group_id}
  483. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  484. data=json.dumps(payload))
  485. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  486. def group_set_permissions(self, group_id, enabled=True):
  487. """
  488. Enable/Disable permissions for a group. Cannot delete group if disabled
  489. :param group_id: id of group
  490. :param enabled: boolean
  491. :return: Keycloak server response
  492. """
  493. params_path = {"realm-name": self.realm_name, "id": group_id}
  494. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  495. data=json.dumps({"enabled": enabled}))
  496. return raise_error_from_response(data_raw, KeycloakGetError)
  497. def group_user_add(self, user_id, group_id):
  498. """
  499. Add user to group (user_id and group_id)
  500. :param user_id: id of user
  501. :param group_id: id of group to add to
  502. :return: Keycloak server response
  503. """
  504. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  505. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  506. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  507. def group_user_remove(self, user_id, group_id):
  508. """
  509. Remove user from group (user_id and group_id)
  510. :param user_id: id of user
  511. :param group_id: id of group to remove from
  512. :return: Keycloak server response
  513. """
  514. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  515. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  516. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  517. def delete_group(self, group_id):
  518. """
  519. Deletes a group in the Realm
  520. :param group_id: id of group to delete
  521. :return: Keycloak server response
  522. """
  523. params_path = {"realm-name": self.realm_name, "id": group_id}
  524. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  525. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  526. def get_clients(self):
  527. """
  528. Returns a list of clients belonging to the realm
  529. ClientRepresentation
  530. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  531. :return: Keycloak server response (ClientRepresentation)
  532. """
  533. params_path = {"realm-name": self.realm_name}
  534. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  535. return raise_error_from_response(data_raw, KeycloakGetError)
  536. def get_client(self, client_id):
  537. """
  538. Get representation of the client
  539. ClientRepresentation
  540. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  541. :param client_id: id of client (not client-id)
  542. :return: Keycloak server response (ClientRepresentation)
  543. """
  544. params_path = {"realm-name": self.realm_name, "id": client_id}
  545. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  546. return raise_error_from_response(data_raw, KeycloakGetError)
  547. def get_client_id(self, client_name):
  548. """
  549. Get internal keycloak client id from client-id.
  550. This is required for further actions against this client.
  551. :param client_name: name in ClientRepresentation
  552. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  553. :return: client_id (uuid as string)
  554. """
  555. clients = self.get_clients()
  556. for client in clients:
  557. if client_name == client.get('name') or client_name == client.get('clientId'):
  558. return client["id"]
  559. return None
  560. def get_client_authz_settings(self, client_id):
  561. """
  562. Get authorization json from client.
  563. :param client_id: id in ClientRepresentation
  564. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  565. :return: Keycloak server response
  566. """
  567. params_path = {"realm-name": self.realm_name, "id": client_id}
  568. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  569. return data_raw
  570. def get_client_authz_resources(self, client_id):
  571. """
  572. Get resources from client.
  573. :param client_id: id in ClientRepresentation
  574. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  575. :return: Keycloak server response
  576. """
  577. params_path = {"realm-name": self.realm_name, "id": client_id}
  578. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  579. return data_raw
  580. def create_client(self, payload, skip_exists=False):
  581. """
  582. Create a client
  583. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  584. :param skip_exists: If true then do not raise an error if client already exists
  585. :param payload: ClientRepresentation
  586. :return: Keycloak server response (UserRepresentation)
  587. """
  588. params_path = {"realm-name": self.realm_name}
  589. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  590. data=json.dumps(payload))
  591. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  592. def update_client(self, client_id, payload):
  593. """
  594. Update a client
  595. :param client_id: Client id
  596. :param payload: ClientRepresentation
  597. :return: Http response
  598. """
  599. params_path = {"realm-name": self.realm_name, "id": client_id}
  600. data_raw = self.connection.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  601. data=json.dumps(payload))
  602. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  603. def delete_client(self, client_id):
  604. """
  605. Get representation of the client
  606. ClientRepresentation
  607. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  608. :param client_id: keycloak client id (not oauth client-id)
  609. :return: Keycloak server response (ClientRepresentation)
  610. """
  611. params_path = {"realm-name": self.realm_name, "id": client_id}
  612. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  613. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  614. def get_realm_roles(self):
  615. """
  616. Get all roles for the realm or client
  617. RoleRepresentation
  618. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  619. :return: Keycloak server response (RoleRepresentation)
  620. """
  621. params_path = {"realm-name": self.realm_name}
  622. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  623. return raise_error_from_response(data_raw, KeycloakGetError)
  624. def get_client_roles(self, client_id):
  625. """
  626. Get all roles for the client
  627. :param client_id: id of client (not client-id)
  628. RoleRepresentation
  629. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  630. :return: Keycloak server response (RoleRepresentation)
  631. """
  632. params_path = {"realm-name": self.realm_name, "id": client_id}
  633. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  634. return raise_error_from_response(data_raw, KeycloakGetError)
  635. def get_client_role(self, client_id, role_name):
  636. """
  637. Get client role id by name
  638. This is required for further actions with this role.
  639. :param client_id: id of client (not client-id)
  640. :param role_name: roles name (not id!)
  641. RoleRepresentation
  642. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  643. :return: role_id
  644. """
  645. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  646. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  647. return raise_error_from_response(data_raw, KeycloakGetError)
  648. def get_client_role_id(self, client_id, role_name):
  649. """
  650. Warning: Deprecated
  651. Get client role id by name
  652. This is required for further actions with this role.
  653. :param client_id: id of client (not client-id)
  654. :param role_name: roles name (not id!)
  655. RoleRepresentation
  656. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  657. :return: role_id
  658. """
  659. role = self.get_client_role(client_id, role_name)
  660. return role.get("id")
  661. def create_client_role(self, client_role_id, payload, skip_exists=False):
  662. """
  663. Create a client role
  664. RoleRepresentation
  665. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  666. :param client_role_id: id of client (not client-id)
  667. :param payload: RoleRepresentation
  668. :param skip_exists: If true then do not raise an error if client role already exists
  669. :return: Keycloak server response (RoleRepresentation)
  670. """
  671. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  672. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  673. data=json.dumps(payload))
  674. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  675. def delete_client_role(self, client_role_id, role_name):
  676. """
  677. Delete a client role
  678. RoleRepresentation
  679. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  680. :param client_role_id: id of client (not client-id)
  681. :param role_name: roles name (not id!)
  682. """
  683. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  684. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  685. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  686. def assign_client_role(self, user_id, client_id, roles):
  687. """
  688. Assign a client role to a user
  689. :param user_id: id of user
  690. :param client_id: id of client (not client-id)
  691. :param roles: roles list or role (use RoleRepresentation)
  692. :return Keycloak server response
  693. """
  694. payload = roles if isinstance(roles, list) else [roles]
  695. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  696. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  697. data=json.dumps(payload))
  698. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  699. def create_realm_role(self, payload, skip_exists=False):
  700. """
  701. Create a new role for the realm or client
  702. :param payload: The role (use RoleRepresentation)
  703. :param skip_exists: If true then do not raise an error if realm role already exists
  704. :return Keycloak server response
  705. """
  706. params_path = {"realm-name": self.realm_name}
  707. data_raw = self.connection.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  708. data=json.dumps(payload))
  709. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  710. def assign_realm_roles(self, user_id, client_id, roles):
  711. """
  712. Assign realm roles to a user
  713. :param user_id: id of user
  714. :param client_id: id of client containing role (not client-id)
  715. :param roles: roles list or role (use RoleRepresentation)
  716. :return Keycloak server response
  717. """
  718. payload = roles if isinstance(roles, list) else [roles]
  719. params_path = {"realm-name": self.realm_name, "id": user_id}
  720. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  721. data=json.dumps(payload))
  722. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  723. def get_client_roles_of_user(self, user_id, client_id):
  724. """
  725. Get all client roles for a user.
  726. :param user_id: id of user
  727. :param client_id: id of client (not client-id)
  728. :return: Keycloak server response (array RoleRepresentation)
  729. """
  730. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  731. def get_available_client_roles_of_user(self, user_id, client_id):
  732. """
  733. Get available client role-mappings for a user.
  734. :param user_id: id of user
  735. :param client_id: id of client (not client-id)
  736. :return: Keycloak server response (array RoleRepresentation)
  737. """
  738. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  739. def get_composite_client_roles_of_user(self, user_id, client_id):
  740. """
  741. Get composite client role-mappings for a user.
  742. :param user_id: id of user
  743. :param client_id: id of client (not client-id)
  744. :return: Keycloak server response (array RoleRepresentation)
  745. """
  746. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  747. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  748. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  749. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  750. return raise_error_from_response(data_raw, KeycloakGetError)
  751. def delete_client_roles_of_user(self, user_id, client_id, roles):
  752. """
  753. Delete client roles from a user.
  754. :param user_id: id of user
  755. :param client_id: id of client containing role (not client-id)
  756. :param roles: roles list or role to delete (use RoleRepresentation)
  757. :return: Keycloak server response
  758. """
  759. payload = roles if isinstance(roles, list) else [roles]
  760. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  761. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  762. data=json.dumps(payload))
  763. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  764. def get_authentication_flows(self):
  765. """
  766. Get authentication flows. Returns all flow details
  767. AuthenticationFlowRepresentation
  768. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  769. :return: Keycloak server response (AuthenticationFlowRepresentation)
  770. """
  771. params_path = {"realm-name": self.realm_name}
  772. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  773. return raise_error_from_response(data_raw, KeycloakGetError)
  774. def create_authentication_flow(self, payload, skip_exists=False):
  775. """
  776. Create a new authentication flow
  777. AuthenticationFlowRepresentation
  778. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  779. :param payload: AuthenticationFlowRepresentation
  780. :param skip_exists: If true then do not raise an error if authentication flow already exists
  781. :return: Keycloak server response (RoleRepresentation)
  782. """
  783. params_path = {"realm-name": self.realm_name}
  784. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  785. data=payload)
  786. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  787. def get_authentication_flow_executions(self, flow_alias):
  788. """
  789. Get authentication flow executions. Returns all execution steps
  790. :param flow_alias: the flow alias
  791. :return: Response(json)
  792. """
  793. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  794. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  795. return raise_error_from_response(data_raw, KeycloakGetError)
  796. def update_authentication_flow_executions(self, payload, flow_alias):
  797. """
  798. Update an authentication flow execution
  799. AuthenticationExecutionInfoRepresentation
  800. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  801. :param payload: AuthenticationExecutionInfoRepresentation
  802. :param flow_alias: The flow alias
  803. :return: Keycloak server response
  804. """
  805. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  806. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  807. data=payload)
  808. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  809. def sync_users(self, storage_id, action):
  810. """
  811. Function to trigger user sync from provider
  812. :param storage_id: The id of the user storage provider
  813. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  814. :return:
  815. """
  816. data = {'action': action}
  817. params_query = {"action": action}
  818. params_path = {"realm-name": self.realm_name, "id": storage_id}
  819. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  820. data=json.dumps(data), **params_query)
  821. return raise_error_from_response(data_raw, KeycloakGetError)
  822. def get_client_scopes(self):
  823. """
  824. Get representation of the client scopes for the realm where we are connected to
  825. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  826. :return: Keycloak server response Array of (ClientScopeRepresentation)
  827. """
  828. params_path = {"realm-name": self.realm_name}
  829. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  830. return raise_error_from_response(data_raw, KeycloakGetError)
  831. def get_client_scope(self, client_scope_id):
  832. """
  833. Get representation of the client scopes for the realm where we are connected to
  834. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  835. :param client_scope_id: The id of the client scope
  836. :return: Keycloak server response (ClientScopeRepresentation)
  837. """
  838. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  839. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  840. return raise_error_from_response(data_raw, KeycloakGetError)
  841. def add_mapper_to_client_scope(self, client_scope_id, payload):
  842. """
  843. Add a mapper to a client scope
  844. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  845. :param client_scope_id: The id of the client scope
  846. :param payload: ProtocolMapperRepresentation
  847. :return: Keycloak server Response
  848. """
  849. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  850. data_raw = self.raw_post(
  851. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  852. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  853. def get_client_secrets(self, client_id):
  854. """
  855. Get representation of the client secrets
  856. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  857. :param client_id: id of client (not client-id)
  858. :return: Keycloak server response (ClientRepresentation)
  859. """
  860. params_path = {"realm-name": self.realm_name, "id": client_id}
  861. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  862. return raise_error_from_response(data_raw, KeycloakGetError)
  863. def raw_get(self, *args, **kwargs):
  864. """
  865. Calls connection.raw_get.
  866. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  867. and try *get* once more.
  868. """
  869. r = self.connection.raw_get(*args, **kwargs)
  870. if 'get' in self.auto_refresh_token and r.status_code == 401:
  871. self.refresh_token()
  872. return self.connection.raw_get(*args, **kwargs)
  873. return r
  874. def raw_post(self, *args, **kwargs):
  875. """
  876. Calls connection.raw_post.
  877. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  878. and try *post* once more.
  879. """
  880. r = self.connection.raw_post(*args, **kwargs)
  881. if 'post' in self.auto_refresh_token and r.status_code == 401:
  882. self.refresh_token()
  883. return self.connection.raw_post(*args, **kwargs)
  884. return r
  885. def raw_put(self, *args, **kwargs):
  886. """
  887. Calls connection.raw_put.
  888. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  889. and try *put* once more.
  890. """
  891. r = self.connection.raw_put(*args, **kwargs)
  892. if 'put' in self.auto_refresh_token and r.status_code == 401:
  893. self.refresh_token()
  894. return self.connection.raw_put(*args, **kwargs)
  895. return r
  896. def raw_delete(self, *args, **kwargs):
  897. """
  898. Calls connection.raw_delete.
  899. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  900. and try *delete* once more.
  901. """
  902. r = self.connection.raw_delete(*args, **kwargs)
  903. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  904. self.refresh_token()
  905. return self.connection.raw_delete(*args, **kwargs)
  906. return r
  907. def get_token(self):
  908. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  909. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  910. client_secret_key=self.client_secret_key,
  911. custom_headers=self.custom_headers)
  912. grant_type = ["password"]
  913. if self.client_secret_key:
  914. grant_type = ["client_credentials"]
  915. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  916. headers = {
  917. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  918. 'Content-Type': 'application/json'
  919. }
  920. if self.custom_headers is not None:
  921. # merge custom headers to main headers
  922. headers.update(self.custom_headers)
  923. self._connection = ConnectionManager(base_url=self.server_url,
  924. headers=headers,
  925. timeout=60,
  926. verify=self.verify)
  927. def refresh_token(self):
  928. refresh_token = self.token.get('refresh_token')
  929. try:
  930. self.token = self.keycloak_openid.refresh_token(refresh_token)
  931. except KeycloakGetError as e:
  932. if e.response_code == 400 and b'Refresh token expired' in e.response_body:
  933. self.get_token()
  934. else:
  935. raise
  936. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))