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.

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