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.

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