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.

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