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.

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