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.

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