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.

1222 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
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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. raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  246. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  247. return data_raw.headers['Location'][_last_slash_idx + 1:]
  248. def users_count(self):
  249. """
  250. User counter
  251. :return: counter
  252. """
  253. params_path = {"realm-name": self.realm_name}
  254. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  255. return raise_error_from_response(data_raw, KeycloakGetError)
  256. def get_user_id(self, username):
  257. """
  258. Get internal keycloak user id from username
  259. This is required for further actions against this user.
  260. UserRepresentation
  261. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  262. :param username: id in UserRepresentation
  263. :return: user_id
  264. """
  265. users = self.get_users(query={"search": username})
  266. return next((user["id"] for user in users if user["username"] == username), None)
  267. def get_user(self, user_id):
  268. """
  269. Get representation of the user
  270. :param user_id: User id
  271. UserRepresentation
  272. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  273. :return: UserRepresentation
  274. """
  275. params_path = {"realm-name": self.realm_name, "id": user_id}
  276. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  277. return raise_error_from_response(data_raw, KeycloakGetError)
  278. def get_user_groups(self, user_id):
  279. """
  280. Returns a list of groups of which the user is a member
  281. :param user_id: User id
  282. :return: user groups list
  283. """
  284. params_path = {"realm-name": self.realm_name, "id": user_id}
  285. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  286. return raise_error_from_response(data_raw, KeycloakGetError)
  287. def update_user(self, user_id, payload):
  288. """
  289. Update the user
  290. :param user_id: User id
  291. :param payload: UserRepresentation
  292. :return: Http response
  293. """
  294. params_path = {"realm-name": self.realm_name, "id": user_id}
  295. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  296. data=json.dumps(payload))
  297. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  298. def delete_user(self, user_id):
  299. """
  300. Delete the user
  301. :param user_id: User id
  302. :return: Http response
  303. """
  304. params_path = {"realm-name": self.realm_name, "id": user_id}
  305. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  306. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  307. def set_user_password(self, user_id, password, temporary=True):
  308. """
  309. Set up a password for the user. If temporary is True, the user will have to reset
  310. the temporary password next time they log in.
  311. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  312. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  313. :param user_id: User id
  314. :param password: New password
  315. :param temporary: True if password is temporary
  316. :return:
  317. """
  318. payload = {"type": "password", "temporary": temporary, "value": password}
  319. params_path = {"realm-name": self.realm_name, "id": user_id}
  320. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  321. data=json.dumps(payload))
  322. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  323. def consents_user(self, user_id):
  324. """
  325. Get consents granted by the user
  326. :param user_id: User id
  327. :return: consents
  328. """
  329. params_path = {"realm-name": self.realm_name, "id": user_id}
  330. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  331. return raise_error_from_response(data_raw, KeycloakGetError)
  332. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  333. """
  334. Send an update account email to the user. An email contains a
  335. link the user can click to perform a set of required actions.
  336. :param user_id: User id
  337. :param payload: A list of actions for the user to complete
  338. :param client_id: Client id (optional)
  339. :param lifespan: Number of seconds after which the generated token expires (optional)
  340. :param redirect_uri: The redirect uri (optional)
  341. :return:
  342. """
  343. params_path = {"realm-name": self.realm_name, "id": user_id}
  344. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  345. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  346. data=payload, **params_query)
  347. return raise_error_from_response(data_raw, KeycloakGetError)
  348. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  349. """
  350. Send a update account email to the user An email contains a
  351. link the user can click to perform a set of required actions.
  352. :param user_id: User id
  353. :param client_id: Client id (optional)
  354. :param redirect_uri: Redirect uri (optional)
  355. :return:
  356. """
  357. params_path = {"realm-name": self.realm_name, "id": user_id}
  358. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  359. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  360. data={}, **params_query)
  361. return raise_error_from_response(data_raw, KeycloakGetError)
  362. def get_sessions(self, user_id):
  363. """
  364. Get sessions associated with the user
  365. :param user_id: id of user
  366. UserSessionRepresentation
  367. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  368. :return: UserSessionRepresentation
  369. """
  370. params_path = {"realm-name": self.realm_name, "id": user_id}
  371. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  372. return raise_error_from_response(data_raw, KeycloakGetError)
  373. def get_server_info(self):
  374. """
  375. Get themes, social providers, auth providers, and event listeners available on this server
  376. ServerInfoRepresentation
  377. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  378. :return: ServerInfoRepresentation
  379. """
  380. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  381. return raise_error_from_response(data_raw, KeycloakGetError)
  382. def get_groups(self):
  383. """
  384. Returns a list of groups belonging to the realm
  385. GroupRepresentation
  386. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  387. :return: array GroupRepresentation
  388. """
  389. params_path = {"realm-name": self.realm_name}
  390. return self.__fetch_all(URL_ADMIN_GROUPS.format(**params_path))
  391. def get_group(self, group_id):
  392. """
  393. Get group by id. Returns full group details
  394. GroupRepresentation
  395. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  396. :param group_id: The group id
  397. :return: Keycloak server response (GroupRepresentation)
  398. """
  399. params_path = {"realm-name": self.realm_name, "id": group_id}
  400. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  401. return raise_error_from_response(data_raw, KeycloakGetError)
  402. def get_subgroups(self, group, path):
  403. """
  404. Utility function to iterate through nested group structures
  405. GroupRepresentation
  406. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  407. :param name: group (GroupRepresentation)
  408. :param path: group path (string)
  409. :return: Keycloak server response (GroupRepresentation)
  410. """
  411. for subgroup in group["subGroups"]:
  412. if subgroup['path'] == path:
  413. return subgroup
  414. elif subgroup["subGroups"]:
  415. for subgroup in group["subGroups"]:
  416. result = self.get_subgroups(subgroup, path)
  417. if result:
  418. return result
  419. # went through the tree without hits
  420. return None
  421. def get_group_members(self, group_id, **query):
  422. """
  423. Get members by group id. Returns group members
  424. GroupRepresentation
  425. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  426. :param group_id: The group id
  427. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  428. :return: Keycloak server response (UserRepresentation)
  429. """
  430. params_path = {"realm-name": self.realm_name, "id": group_id}
  431. return self.__fetch_all(URL_ADMIN_GROUP_MEMBERS.format(**params_path), query)
  432. def get_group_by_path(self, path, search_in_subgroups=False):
  433. """
  434. Get group id based on name or path.
  435. A straight name or path match with a top-level group will return first.
  436. Subgroups are traversed, the first to match path (or name with path) is returned.
  437. GroupRepresentation
  438. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  439. :param path: group path
  440. :param search_in_subgroups: True if want search in the subgroups
  441. :return: Keycloak server response (GroupRepresentation)
  442. """
  443. groups = self.get_groups()
  444. # TODO: Review this code is necessary
  445. for group in groups:
  446. if group['path'] == path:
  447. return group
  448. elif search_in_subgroups and group["subGroups"]:
  449. for group in group["subGroups"]:
  450. if group['path'] == path:
  451. return group
  452. res = self.get_subgroups(group, path)
  453. if res != None:
  454. return res
  455. return None
  456. def create_group(self, payload, parent=None, skip_exists=False):
  457. """
  458. Creates a group in the Realm
  459. :param payload: GroupRepresentation
  460. :param parent: parent group's id. Required to create a sub-group.
  461. :param skip_exists: If true then do not raise an error if it already exists
  462. GroupRepresentation
  463. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  464. :return: Http response
  465. """
  466. if parent is None:
  467. params_path = {"realm-name": self.realm_name}
  468. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  469. data=json.dumps(payload))
  470. else:
  471. params_path = {"realm-name": self.realm_name, "id": parent, }
  472. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  473. data=json.dumps(payload))
  474. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  475. def update_group(self, group_id, payload):
  476. """
  477. Update group, ignores subgroups.
  478. :param group_id: id of group
  479. :param payload: GroupRepresentation with updated information.
  480. GroupRepresentation
  481. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  482. :return: Http response
  483. """
  484. params_path = {"realm-name": self.realm_name, "id": group_id}
  485. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  486. data=json.dumps(payload))
  487. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  488. def group_set_permissions(self, group_id, enabled=True):
  489. """
  490. Enable/Disable permissions for a group. Cannot delete group if disabled
  491. :param group_id: id of group
  492. :param enabled: boolean
  493. :return: Keycloak server response
  494. """
  495. params_path = {"realm-name": self.realm_name, "id": group_id}
  496. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  497. data=json.dumps({"enabled": enabled}))
  498. return raise_error_from_response(data_raw, KeycloakGetError)
  499. def group_user_add(self, user_id, group_id):
  500. """
  501. Add user to group (user_id and group_id)
  502. :param user_id: id of user
  503. :param group_id: id of group to add to
  504. :return: Keycloak server response
  505. """
  506. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  507. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  508. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  509. def group_user_remove(self, user_id, group_id):
  510. """
  511. Remove user from group (user_id and group_id)
  512. :param user_id: id of user
  513. :param group_id: id of group to remove from
  514. :return: Keycloak server response
  515. """
  516. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  517. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  518. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  519. def delete_group(self, group_id):
  520. """
  521. Deletes a group in the Realm
  522. :param group_id: id of group to delete
  523. :return: Keycloak server response
  524. """
  525. params_path = {"realm-name": self.realm_name, "id": group_id}
  526. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  527. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  528. def get_clients(self):
  529. """
  530. Returns a list of clients belonging to the realm
  531. ClientRepresentation
  532. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  533. :return: Keycloak server response (ClientRepresentation)
  534. """
  535. params_path = {"realm-name": self.realm_name}
  536. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  537. return raise_error_from_response(data_raw, KeycloakGetError)
  538. def get_client(self, client_id):
  539. """
  540. Get representation of the client
  541. ClientRepresentation
  542. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  543. :param client_id: id of client (not client-id)
  544. :return: Keycloak server response (ClientRepresentation)
  545. """
  546. params_path = {"realm-name": self.realm_name, "id": client_id}
  547. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  548. return raise_error_from_response(data_raw, KeycloakGetError)
  549. def get_client_id(self, client_name):
  550. """
  551. Get internal keycloak client id from client-id.
  552. This is required for further actions against this client.
  553. :param client_name: name in ClientRepresentation
  554. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  555. :return: client_id (uuid as string)
  556. """
  557. clients = self.get_clients()
  558. for client in clients:
  559. if client_name == client.get('name') or client_name == client.get('clientId'):
  560. return client["id"]
  561. return None
  562. def get_client_authz_settings(self, client_id):
  563. """
  564. Get authorization json from client.
  565. :param client_id: id in ClientRepresentation
  566. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  567. :return: Keycloak server response
  568. """
  569. params_path = {"realm-name": self.realm_name, "id": client_id}
  570. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  571. return data_raw
  572. def get_client_authz_resources(self, client_id):
  573. """
  574. Get resources from client.
  575. :param client_id: id in ClientRepresentation
  576. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  577. :return: Keycloak server response
  578. """
  579. params_path = {"realm-name": self.realm_name, "id": client_id}
  580. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  581. return data_raw
  582. def create_client(self, payload, skip_exists=False):
  583. """
  584. Create a client
  585. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  586. :param skip_exists: If true then do not raise an error if client already exists
  587. :param payload: ClientRepresentation
  588. :return: Keycloak server response (UserRepresentation)
  589. """
  590. params_path = {"realm-name": self.realm_name}
  591. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  592. data=json.dumps(payload))
  593. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  594. def update_client(self, client_id, payload):
  595. """
  596. Update a client
  597. :param client_id: Client id
  598. :param payload: ClientRepresentation
  599. :return: Http response
  600. """
  601. params_path = {"realm-name": self.realm_name, "id": client_id}
  602. data_raw = self.connection.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  603. data=json.dumps(payload))
  604. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  605. def delete_client(self, client_id):
  606. """
  607. Get representation of the client
  608. ClientRepresentation
  609. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  610. :param client_id: keycloak client id (not oauth client-id)
  611. :return: Keycloak server response (ClientRepresentation)
  612. """
  613. params_path = {"realm-name": self.realm_name, "id": client_id}
  614. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  615. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  616. def get_realm_roles(self):
  617. """
  618. Get all roles for the realm or client
  619. RoleRepresentation
  620. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  621. :return: Keycloak server response (RoleRepresentation)
  622. """
  623. params_path = {"realm-name": self.realm_name}
  624. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  625. return raise_error_from_response(data_raw, KeycloakGetError)
  626. def get_client_roles(self, client_id):
  627. """
  628. Get all roles for the client
  629. :param client_id: id of client (not client-id)
  630. RoleRepresentation
  631. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  632. :return: Keycloak server response (RoleRepresentation)
  633. """
  634. params_path = {"realm-name": self.realm_name, "id": client_id}
  635. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  636. return raise_error_from_response(data_raw, KeycloakGetError)
  637. def get_client_role(self, client_id, role_name):
  638. """
  639. Get client role id by name
  640. This is required for further actions with this role.
  641. :param client_id: id of client (not client-id)
  642. :param role_name: roles name (not id!)
  643. RoleRepresentation
  644. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  645. :return: role_id
  646. """
  647. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  648. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  649. return raise_error_from_response(data_raw, KeycloakGetError)
  650. def get_client_role_id(self, client_id, role_name):
  651. """
  652. Warning: Deprecated
  653. Get client role id by name
  654. This is required for further actions with this role.
  655. :param client_id: id of client (not client-id)
  656. :param role_name: roles name (not id!)
  657. RoleRepresentation
  658. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  659. :return: role_id
  660. """
  661. role = self.get_client_role(client_id, role_name)
  662. return role.get("id")
  663. def create_client_role(self, client_role_id, payload, skip_exists=False):
  664. """
  665. Create a client role
  666. RoleRepresentation
  667. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  668. :param client_role_id: id of client (not client-id)
  669. :param payload: RoleRepresentation
  670. :param skip_exists: If true then do not raise an error if client role already exists
  671. :return: Keycloak server response (RoleRepresentation)
  672. """
  673. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  674. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  675. data=json.dumps(payload))
  676. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  677. def delete_client_role(self, client_role_id, role_name):
  678. """
  679. Delete a client role
  680. RoleRepresentation
  681. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  682. :param client_role_id: id of client (not client-id)
  683. :param role_name: roles name (not id!)
  684. """
  685. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  686. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  687. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  688. def assign_client_role(self, user_id, client_id, roles):
  689. """
  690. Assign a client role to a user
  691. :param user_id: id of user
  692. :param client_id: id of client (not client-id)
  693. :param roles: roles list or role (use RoleRepresentation)
  694. :return Keycloak server response
  695. """
  696. payload = roles if isinstance(roles, list) else [roles]
  697. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  698. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  699. data=json.dumps(payload))
  700. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  701. def create_realm_role(self, payload, skip_exists=False):
  702. """
  703. Create a new role for the realm or client
  704. :param payload: The role (use RoleRepresentation)
  705. :param skip_exists: If true then do not raise an error if realm role already exists
  706. :return Keycloak server response
  707. """
  708. params_path = {"realm-name": self.realm_name}
  709. data_raw = self.connection.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  710. data=json.dumps(payload))
  711. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  712. def assign_realm_roles(self, user_id, client_id, roles):
  713. """
  714. Assign realm roles to a user
  715. :param user_id: id of user
  716. :param client_id: id of client containing role (not client-id)
  717. :param roles: roles list or role (use RoleRepresentation)
  718. :return Keycloak server response
  719. """
  720. payload = roles if isinstance(roles, list) else [roles]
  721. params_path = {"realm-name": self.realm_name, "id": user_id}
  722. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  723. data=json.dumps(payload))
  724. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  725. def get_client_roles_of_user(self, user_id, client_id):
  726. """
  727. Get all client roles for a user.
  728. :param user_id: id of user
  729. :param client_id: id of client (not client-id)
  730. :return: Keycloak server response (array RoleRepresentation)
  731. """
  732. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  733. def get_available_client_roles_of_user(self, user_id, client_id):
  734. """
  735. Get available client role-mappings for a user.
  736. :param user_id: id of user
  737. :param client_id: id of client (not client-id)
  738. :return: Keycloak server response (array RoleRepresentation)
  739. """
  740. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  741. def get_composite_client_roles_of_user(self, user_id, client_id):
  742. """
  743. Get composite client role-mappings for a user.
  744. :param user_id: id of user
  745. :param client_id: id of client (not client-id)
  746. :return: Keycloak server response (array RoleRepresentation)
  747. """
  748. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  749. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  750. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  751. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  752. return raise_error_from_response(data_raw, KeycloakGetError)
  753. def delete_client_roles_of_user(self, user_id, client_id, roles):
  754. """
  755. Delete client roles from a user.
  756. :param user_id: id of user
  757. :param client_id: id of client containing role (not client-id)
  758. :param roles: roles list or role to delete (use RoleRepresentation)
  759. :return: Keycloak server response
  760. """
  761. payload = roles if isinstance(roles, list) else [roles]
  762. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  763. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  764. data=json.dumps(payload))
  765. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  766. def get_authentication_flows(self):
  767. """
  768. Get authentication flows. Returns all flow details
  769. AuthenticationFlowRepresentation
  770. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  771. :return: Keycloak server response (AuthenticationFlowRepresentation)
  772. """
  773. params_path = {"realm-name": self.realm_name}
  774. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  775. return raise_error_from_response(data_raw, KeycloakGetError)
  776. def create_authentication_flow(self, payload, skip_exists=False):
  777. """
  778. Create a new authentication flow
  779. AuthenticationFlowRepresentation
  780. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  781. :param payload: AuthenticationFlowRepresentation
  782. :param skip_exists: If true then do not raise an error if authentication flow already exists
  783. :return: Keycloak server response (RoleRepresentation)
  784. """
  785. params_path = {"realm-name": self.realm_name}
  786. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  787. data=payload)
  788. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  789. def get_authentication_flow_executions(self, flow_alias):
  790. """
  791. Get authentication flow executions. Returns all execution steps
  792. :param flow_alias: the flow alias
  793. :return: Response(json)
  794. """
  795. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  796. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  797. return raise_error_from_response(data_raw, KeycloakGetError)
  798. def update_authentication_flow_executions(self, payload, flow_alias):
  799. """
  800. Update an authentication flow execution
  801. AuthenticationExecutionInfoRepresentation
  802. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  803. :param payload: AuthenticationExecutionInfoRepresentation
  804. :param flow_alias: The flow alias
  805. :return: Keycloak server response
  806. """
  807. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  808. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  809. data=payload)
  810. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  811. def sync_users(self, storage_id, action):
  812. """
  813. Function to trigger user sync from provider
  814. :param storage_id: The id of the user storage provider
  815. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  816. :return:
  817. """
  818. data = {'action': action}
  819. params_query = {"action": action}
  820. params_path = {"realm-name": self.realm_name, "id": storage_id}
  821. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  822. data=json.dumps(data), **params_query)
  823. return raise_error_from_response(data_raw, KeycloakGetError)
  824. def get_client_scopes(self):
  825. """
  826. Get representation of the client scopes for the realm where we are connected to
  827. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  828. :return: Keycloak server response Array of (ClientScopeRepresentation)
  829. """
  830. params_path = {"realm-name": self.realm_name}
  831. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  832. return raise_error_from_response(data_raw, KeycloakGetError)
  833. def get_client_scope(self, client_scope_id):
  834. """
  835. Get representation of the client scopes for the realm where we are connected to
  836. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  837. :param client_scope_id: The id of the client scope
  838. :return: Keycloak server response (ClientScopeRepresentation)
  839. """
  840. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  841. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  842. return raise_error_from_response(data_raw, KeycloakGetError)
  843. def add_mapper_to_client_scope(self, client_scope_id, payload):
  844. """
  845. Add a mapper to a client scope
  846. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  847. :param client_scope_id: The id of the client scope
  848. :param payload: ProtocolMapperRepresentation
  849. :return: Keycloak server Response
  850. """
  851. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  852. data_raw = self.raw_post(
  853. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  854. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  855. def generate_client_secrets(self, client_id):
  856. """
  857. Generate a new secret for the client
  858. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  859. :param client_id: id of client (not client-id)
  860. :return: Keycloak server response (ClientRepresentation)
  861. """
  862. params_path = {"realm-name": self.realm_name, "id": client_id}
  863. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  864. return raise_error_from_response(data_raw, KeycloakGetError)
  865. def get_client_secrets(self, client_id):
  866. """
  867. Get representation of the client secrets
  868. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  869. :param client_id: id of client (not client-id)
  870. :return: Keycloak server response (ClientRepresentation)
  871. """
  872. params_path = {"realm-name": self.realm_name, "id": client_id}
  873. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  874. return raise_error_from_response(data_raw, KeycloakGetError)
  875. def raw_get(self, *args, **kwargs):
  876. """
  877. Calls connection.raw_get.
  878. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  879. and try *get* once more.
  880. """
  881. r = self.connection.raw_get(*args, **kwargs)
  882. if 'get' in self.auto_refresh_token and r.status_code == 401:
  883. self.refresh_token()
  884. return self.connection.raw_get(*args, **kwargs)
  885. return r
  886. def raw_post(self, *args, **kwargs):
  887. """
  888. Calls connection.raw_post.
  889. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  890. and try *post* once more.
  891. """
  892. r = self.connection.raw_post(*args, **kwargs)
  893. if 'post' in self.auto_refresh_token and r.status_code == 401:
  894. self.refresh_token()
  895. return self.connection.raw_post(*args, **kwargs)
  896. return r
  897. def raw_put(self, *args, **kwargs):
  898. """
  899. Calls connection.raw_put.
  900. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  901. and try *put* once more.
  902. """
  903. r = self.connection.raw_put(*args, **kwargs)
  904. if 'put' in self.auto_refresh_token and r.status_code == 401:
  905. self.refresh_token()
  906. return self.connection.raw_put(*args, **kwargs)
  907. return r
  908. def raw_delete(self, *args, **kwargs):
  909. """
  910. Calls connection.raw_delete.
  911. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  912. and try *delete* once more.
  913. """
  914. r = self.connection.raw_delete(*args, **kwargs)
  915. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  916. self.refresh_token()
  917. return self.connection.raw_delete(*args, **kwargs)
  918. return r
  919. def get_token(self):
  920. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  921. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  922. client_secret_key=self.client_secret_key,
  923. custom_headers=self.custom_headers)
  924. grant_type = ["password"]
  925. if self.client_secret_key:
  926. grant_type = ["client_credentials"]
  927. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  928. headers = {
  929. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  930. 'Content-Type': 'application/json'
  931. }
  932. if self.custom_headers is not None:
  933. # merge custom headers to main headers
  934. headers.update(self.custom_headers)
  935. self._connection = ConnectionManager(base_url=self.server_url,
  936. headers=headers,
  937. timeout=60,
  938. verify=self.verify)
  939. def refresh_token(self):
  940. refresh_token = self.token.get('refresh_token')
  941. try:
  942. self.token = self.keycloak_openid.refresh_token(refresh_token)
  943. except KeycloakGetError as e:
  944. if e.response_code == 400 and b'Refresh token expired' in e.response_body:
  945. self.get_token()
  946. else:
  947. raise
  948. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))