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.

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