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.

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