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.

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