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.

951 lines
36 KiB

7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
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
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 group_set_permissions(self, group_id, enabled=True):
  394. """
  395. Enable/Disable permissions for a group. Cannot delete group if disabled
  396. :param group_id: id of group
  397. :param enabled: boolean
  398. :return: Keycloak server response
  399. """
  400. params_path = {"realm-name": self.realm_name, "id": group_id}
  401. data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  402. data=json.dumps({"enabled": enabled}))
  403. return raise_error_from_response(data_raw, KeycloakGetError)
  404. def group_user_add(self, user_id, group_id):
  405. """
  406. Add user to group (user_id and group_id)
  407. :param group_id: id of group
  408. :param user_id: id of user
  409. :param group_id: id of group to add to
  410. :return: Keycloak server response
  411. """
  412. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  413. data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  414. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  415. def group_user_remove(self, user_id, group_id):
  416. """
  417. Remove user from group (user_id and group_id)
  418. :param group_id: id of group
  419. :param user_id: id of user
  420. :param group_id: id of group to add to
  421. :return: Keycloak server response
  422. """
  423. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  424. data_raw = self.connection.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  425. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  426. def delete_group(self, group_id):
  427. """
  428. Deletes a group in the Realm
  429. :param group_id: id of group to delete
  430. :return: Keycloak server response
  431. """
  432. params_path = {"realm-name": self.realm_name, "id": group_id}
  433. data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  434. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  435. def get_clients(self):
  436. """
  437. Get clients belonging to the realm Returns a list of clients belonging to the realm
  438. ClientRepresentation
  439. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  440. :return: Keycloak server response (ClientRepresentation)
  441. """
  442. params_path = {"realm-name": self.realm_name}
  443. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  444. return raise_error_from_response(data_raw, KeycloakGetError)
  445. def get_client(self, client_id):
  446. """
  447. Get representation of the client
  448. ClientRepresentation
  449. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  450. :param client_id: id of client (not client-id)
  451. :return: Keycloak server response (ClientRepresentation)
  452. """
  453. params_path = {"realm-name": self.realm_name, "id": client_id}
  454. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  455. return raise_error_from_response(data_raw, KeycloakGetError)
  456. def get_client_id(self, client_name):
  457. """
  458. Get internal keycloak client id from client-id.
  459. This is required for further actions against this client.
  460. :param client_name: name in ClientRepresentation
  461. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  462. :return: client_id (uuid as string)
  463. """
  464. clients = self.get_clients()
  465. for client in clients:
  466. if client_name == client.get('name') or client_name == client.get('clientId'):
  467. return client["id"]
  468. return None
  469. def get_client_authz_settings(self, client_id):
  470. """
  471. Get authorization json from client.
  472. :param client_id: id in ClientRepresentation
  473. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  474. :return: Keycloak server response
  475. """
  476. params_path = {"realm-name": self.realm_name, "id": client_id}
  477. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  478. return data_raw
  479. def get_client_authz_resources(self, client_id):
  480. """
  481. Get resources from client.
  482. :param client_id: id in ClientRepresentation
  483. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  484. :return: Keycloak server response
  485. """
  486. params_path = {"realm-name": self.realm_name, "id": client_id}
  487. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  488. return data_raw
  489. def create_client(self, payload, skip_exists=False):
  490. """
  491. Create a client
  492. ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  493. :param skip_exists: Skip if client already exist.
  494. :param payload: ClientRepresentation
  495. :return: Keycloak server response (UserRepresentation)
  496. """
  497. params_path = {"realm-name": self.realm_name}
  498. data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  499. data=json.dumps(payload))
  500. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  501. def delete_client(self, client_id):
  502. """
  503. Get representation of the client
  504. ClientRepresentation
  505. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  506. :param client_id: keycloak client id (not oauth client-id)
  507. :return: Keycloak server response (ClientRepresentation)
  508. """
  509. params_path = {"realm-name": self.realm_name, "id": client_id}
  510. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  511. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  512. def get_realm_roles(self):
  513. """
  514. Get all roles for the realm or client
  515. RoleRepresentation
  516. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  517. :return: Keycloak server response (RoleRepresentation)
  518. """
  519. params_path = {"realm-name": self.realm_name}
  520. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  521. return raise_error_from_response(data_raw, KeycloakGetError)
  522. def get_client_roles(self, client_id):
  523. """
  524. Get all roles for the client
  525. :param client_id: id of client (not client-id)
  526. RoleRepresentation
  527. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  528. :return: Keycloak server response (RoleRepresentation)
  529. """
  530. params_path = {"realm-name": self.realm_name, "id": client_id}
  531. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  532. return raise_error_from_response(data_raw, KeycloakGetError)
  533. def get_client_role(self, client_id, role_name):
  534. """
  535. Get client role id by name
  536. This is required for further actions with this role.
  537. :param client_id: id of client (not client-id)
  538. :param role_name: roles name (not id!)
  539. RoleRepresentation
  540. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  541. :return: role_id
  542. """
  543. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  544. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  545. return raise_error_from_response(data_raw, KeycloakGetError)
  546. def get_client_role_id(self, client_id, role_name):
  547. """
  548. Warning: Deprecated
  549. Get client role id by name
  550. This is required for further actions with this role.
  551. :param client_id: id of client (not client-id)
  552. :param role_name: roles name (not id!)
  553. RoleRepresentation
  554. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  555. :return: role_id
  556. """
  557. role = self.get_client_role(client_id, role_name)
  558. return role.get("id")
  559. def create_client_role(self, client_role_id, payload, skip_exists=False):
  560. """
  561. Create a client role
  562. RoleRepresentation
  563. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  564. :param client_role_id: id of client (not client-id)
  565. :param payload: RoleRepresentation
  566. :return: Keycloak server response (RoleRepresentation)
  567. """
  568. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  569. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  570. data=json.dumps(payload))
  571. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  572. def delete_client_role(self, client_role_id, role_name):
  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 role_name: roles name (not id!)
  579. """
  580. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  581. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  582. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  583. def assign_client_role(self, user_id, client_id, roles):
  584. """
  585. Assign a client role to a user
  586. :param client_id: id of client (not client-id)
  587. :param user_id: id of user
  588. :param client_id: id of client containing role,
  589. :param roles: roles list or role (use RoleRepresentation)
  590. :return Keycloak server response
  591. """
  592. payload = roles if isinstance(roles, list) else [roles]
  593. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  594. data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  595. data=json.dumps(payload))
  596. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  597. def get_client_roles_of_user(self, user_id, client_id):
  598. """
  599. Get all client roles for a user.
  600. :param client_id: id of client (not client-id)
  601. :param user_id: id of user
  602. :return: Keycloak server response (array RoleRepresentation)
  603. """
  604. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  605. def get_available_client_roles_of_user(self, user_id, client_id):
  606. """
  607. Get available client role-mappings for a user.
  608. :param client_id: id of client (not client-id)
  609. :param user_id: id of user
  610. :return: Keycloak server response (array RoleRepresentation)
  611. """
  612. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  613. def get_composite_client_roles_of_user(self, user_id, client_id):
  614. """
  615. Get composite client role-mappings for a user.
  616. :param client_id: id of client (not client-id)
  617. :param user_id: id of user
  618. :return: Keycloak server response (array RoleRepresentation)
  619. """
  620. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  621. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  622. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  623. data_raw = self.connection.raw_get(client_level_role_mapping_url.format(**params_path))
  624. return raise_error_from_response(data_raw, KeycloakGetError)
  625. def delete_client_roles_of_user(self, user_id, client_id, roles):
  626. """
  627. Delete client roles from a user.
  628. :param client_id: id of client (not client-id)
  629. :param user_id: id of user
  630. :param client_id: id of client containing role,
  631. :param roles: roles list or role to delete (use RoleRepresentation)
  632. :return: Keycloak server response
  633. """
  634. payload = roles if isinstance(roles, list) else [roles]
  635. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  636. data_raw = self.connection.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  637. data=json.dumps(payload))
  638. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  639. def get_authentication_flows(self):
  640. """
  641. Get authentication flows. Returns all flow details
  642. AuthenticationFlowRepresentation
  643. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  644. :return: Keycloak server response (AuthenticationFlowRepresentation)
  645. """
  646. params_path = {"realm-name": self.realm_name}
  647. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  648. return raise_error_from_response(data_raw, KeycloakGetError)
  649. def create_authentication_flow(self, payload, skip_exists=False):
  650. """
  651. Create a new authentication flow
  652. AuthenticationFlowRepresentation
  653. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  654. :param payload: AuthenticationFlowRepresentation
  655. :return: Keycloak server response (RoleRepresentation)
  656. """
  657. params_path = {"realm-name": self.realm_name}
  658. data_raw = self.connection.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  659. data=payload)
  660. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  661. def get_authentication_flow_executions(self, flow_alias):
  662. """
  663. Get authentication flow executions. Returns all execution steps
  664. :return: Response(json)
  665. """
  666. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  667. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  668. return raise_error_from_response(data_raw, KeycloakGetError)
  669. def update_authentication_flow_executions(self, payload, flow_alias):
  670. """
  671. Update an authentication flow execution
  672. AuthenticationExecutionInfoRepresentation
  673. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationexecutioninforepresentation
  674. :param payload: AuthenticationExecutionInfoRepresentation
  675. :return: Keycloak server response
  676. """
  677. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  678. data_raw = self.connection.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  679. data=payload)
  680. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  681. def sync_users(self, storage_id, action):
  682. """
  683. Function to trigger user sync from provider
  684. :param storage_id:
  685. :param action:
  686. :return:
  687. """
  688. data = {'action': action}
  689. params_query = {"action": action}
  690. params_path = {"realm-name": self.realm_name, "id": storage_id}
  691. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  692. data=json.dumps(data), **params_query)
  693. return raise_error_from_response(data_raw, KeycloakGetError)
  694. def get_client_scopes(self):
  695. """
  696. Get representation of the client scopes for the realm where we are connected to
  697. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientscopes
  698. :return: Keycloak server response Array of (ClientScopeRepresentation)
  699. """
  700. params_path = {"realm-name": self.realm_name}
  701. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  702. return raise_error_from_response(data_raw, KeycloakGetError)
  703. def get_client_scope(self, client_scope_id):
  704. """
  705. Get representation of the client scopes for the realm where we are connected to
  706. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientscopes
  707. :return: Keycloak server response (ClientScopeRepresentation)
  708. """
  709. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  710. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  711. return raise_error_from_response(data_raw, KeycloakGetError)
  712. def add_mapper_to_client_scope(self, client_scope_id, payload):
  713. """
  714. Add a mapper to a client scope
  715. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_create_mapper
  716. :param payload: ProtocolMapperRepresentation
  717. :return: Keycloak server Response
  718. """
  719. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  720. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  721. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  722. def get_client_secrets(self, client_id):
  723. """
  724. Get representation of the client secrets
  725. https://www.keycloak.org/docs-api/4.5/rest-api/index.html#_getclientsecret
  726. :param client_id: id of client (not client-id)
  727. :return: Keycloak server response (ClientRepresentation)
  728. """
  729. params_path = {"realm-name": self.realm_name, "id": client_id}
  730. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  731. return raise_error_from_response(data_raw, KeycloakGetError)