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.

1192 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
7 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
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, roles):
  703. """
  704. Assign realm roles to a user
  705. :param user_id: id of user
  706. :param roles: roles list or role (use RoleRepresentation)
  707. :return Keycloak server response
  708. """
  709. payload = roles if isinstance(roles, list) else [roles]
  710. params_path = {"realm-name": self.realm_name, "id": user_id}
  711. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  712. data=json.dumps(payload))
  713. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  714. def get_client_roles_of_user(self, user_id, client_id):
  715. """
  716. Get all client roles for a user.
  717. :param client_id: id of client (not client-id)
  718. :param user_id: id of user
  719. :return: Keycloak server response (array RoleRepresentation)
  720. """
  721. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  722. def get_available_client_roles_of_user(self, user_id, client_id):
  723. """
  724. Get available client role-mappings for a user.
  725. :param client_id: id of client (not client-id)
  726. :param user_id: id of user
  727. :return: Keycloak server response (array RoleRepresentation)
  728. """
  729. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  730. def get_composite_client_roles_of_user(self, user_id, client_id):
  731. """
  732. Get composite client role-mappings for a user.
  733. :param client_id: id of client (not client-id)
  734. :param user_id: id of user
  735. :return: Keycloak server response (array RoleRepresentation)
  736. """
  737. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  738. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  739. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  740. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  741. return raise_error_from_response(data_raw, KeycloakGetError)
  742. def delete_client_roles_of_user(self, user_id, client_id, roles):
  743. """
  744. Delete client roles from a user.
  745. :param client_id: id of client (not client-id)
  746. :param user_id: id of user
  747. :param client_id: id of client containing role,
  748. :param roles: roles list or role to delete (use RoleRepresentation)
  749. :return: Keycloak server response
  750. """
  751. payload = roles if isinstance(roles, list) else [roles]
  752. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  753. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  754. data=json.dumps(payload))
  755. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  756. def get_authentication_flows(self):
  757. """
  758. Get authentication flows. Returns all flow details
  759. AuthenticationFlowRepresentation
  760. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  761. :return: Keycloak server response (AuthenticationFlowRepresentation)
  762. """
  763. params_path = {"realm-name": self.realm_name}
  764. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  765. return raise_error_from_response(data_raw, KeycloakGetError)
  766. def create_authentication_flow(self, payload, skip_exists=False):
  767. """
  768. Create a new authentication flow
  769. AuthenticationFlowRepresentation
  770. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  771. :param payload: AuthenticationFlowRepresentation
  772. :return: Keycloak server response (RoleRepresentation)
  773. """
  774. params_path = {"realm-name": self.realm_name}
  775. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  776. data=payload)
  777. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  778. def get_authentication_flow_executions(self, flow_alias):
  779. """
  780. Get authentication flow executions. Returns all execution steps
  781. :return: Response(json)
  782. """
  783. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  784. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  785. return raise_error_from_response(data_raw, KeycloakGetError)
  786. def update_authentication_flow_executions(self, payload, flow_alias):
  787. """
  788. Update an authentication flow execution
  789. AuthenticationExecutionInfoRepresentation
  790. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationexecutioninforepresentation
  791. :param payload: AuthenticationExecutionInfoRepresentation
  792. :return: Keycloak server response
  793. """
  794. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  795. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  796. data=payload)
  797. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  798. def sync_users(self, storage_id, action):
  799. """
  800. Function to trigger user sync from provider
  801. :param storage_id:
  802. :param action:
  803. :return:
  804. """
  805. data = {'action': action}
  806. params_query = {"action": action}
  807. params_path = {"realm-name": self.realm_name, "id": storage_id}
  808. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  809. data=json.dumps(data), **params_query)
  810. return raise_error_from_response(data_raw, KeycloakGetError)
  811. def get_client_scopes(self):
  812. """
  813. Get representation of the client scopes for the realm where we are connected to
  814. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientscopes
  815. :return: Keycloak server response Array of (ClientScopeRepresentation)
  816. """
  817. params_path = {"realm-name": self.realm_name}
  818. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  819. return raise_error_from_response(data_raw, KeycloakGetError)
  820. def get_client_scope(self, client_scope_id):
  821. """
  822. Get representation of the client scopes for the realm where we are connected to
  823. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientscopes
  824. :return: Keycloak server response (ClientScopeRepresentation)
  825. """
  826. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  827. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  828. return raise_error_from_response(data_raw, KeycloakGetError)
  829. def add_mapper_to_client_scope(self, client_scope_id, payload):
  830. """
  831. Add a mapper to a client scope
  832. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_create_mapper
  833. :param payload: ProtocolMapperRepresentation
  834. :return: Keycloak server Response
  835. """
  836. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  837. data_raw = self.raw_post(
  838. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  839. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  840. def get_client_secrets(self, client_id):
  841. """
  842. Get representation of the client secrets
  843. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientsecret
  844. :param client_id: id of client (not client-id)
  845. :return: Keycloak server response (ClientRepresentation)
  846. """
  847. params_path = {"realm-name": self.realm_name, "id": client_id}
  848. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  849. return raise_error_from_response(data_raw, KeycloakGetError)
  850. def raw_get(self, *args, **kwargs):
  851. """
  852. Calls connection.raw_get.
  853. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  854. and try *get* once more.
  855. """
  856. r = self.connection.raw_get(*args, **kwargs)
  857. if 'get' in self.auto_refresh_token and r.status_code == 401:
  858. self.refresh_token()
  859. return self.connection.raw_get(*args, **kwargs)
  860. return r
  861. def raw_post(self, *args, **kwargs):
  862. """
  863. Calls connection.raw_post.
  864. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  865. and try *post* once more.
  866. """
  867. r = self.connection.raw_post(*args, **kwargs)
  868. if 'post' in self.auto_refresh_token and r.status_code == 401:
  869. self.refresh_token()
  870. return self.connection.raw_post(*args, **kwargs)
  871. return r
  872. def raw_put(self, *args, **kwargs):
  873. """
  874. Calls connection.raw_put.
  875. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  876. and try *put* once more.
  877. """
  878. r = self.connection.raw_put(*args, **kwargs)
  879. if 'put' in self.auto_refresh_token and r.status_code == 401:
  880. self.refresh_token()
  881. return self.connection.raw_put(*args, **kwargs)
  882. return r
  883. def raw_delete(self, *args, **kwargs):
  884. """
  885. Calls connection.raw_delete.
  886. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  887. and try *delete* once more.
  888. """
  889. r = self.connection.raw_delete(*args, **kwargs)
  890. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  891. self.refresh_token()
  892. return self.connection.raw_delete(*args, **kwargs)
  893. return r
  894. def get_token(self):
  895. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  896. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  897. client_secret_key=self.client_secret_key,
  898. custom_headers=self.custom_headers)
  899. grant_type = ["password"]
  900. if self.client_secret_key:
  901. grant_type = ["client_credentials"]
  902. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  903. headers = {
  904. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  905. 'Content-Type': 'application/json'
  906. }
  907. if self.custom_headers is not None:
  908. # merge custom headers to main headers
  909. headers.update(self.custom_headers)
  910. self._connection = ConnectionManager(base_url=self.server_url,
  911. headers=headers,
  912. timeout=60,
  913. verify=self.verify)
  914. def refresh_token(self):
  915. refresh_token = self.token.get('refresh_token')
  916. try:
  917. self.token = self.keycloak_openid.refresh_token(refresh_token)
  918. except KeycloakGetError as e:
  919. if e.response_code == 400 and b'Refresh token expired' in e.response_body:
  920. self.get_token()
  921. else:
  922. raise
  923. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))