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.

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