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.

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