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.

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