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.

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