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.

969 lines
37 KiB

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