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.

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