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.

1009 lines
38 KiB

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