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.

1500 lines
57 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 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
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
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 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 keycloak.urls_patterns import URL_ADMIN_GROUPS_REALM_ROLES, \
  29. URL_ADMIN_GET_GROUPS_REALM_ROLES, URL_ADMIN_REALM_ROLES_ROLE_BY_NAME, URL_ADMIN_GROUPS_CLIENT_ROLES
  30. from .connection import ConnectionManager
  31. from .exceptions import raise_error_from_response, KeycloakGetError
  32. from .keycloak_openid import KeycloakOpenID
  33. from .urls_patterns import URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_CLIENT_ROLES, \
  34. URL_ADMIN_GET_SESSIONS, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_UPDATE_ACCOUNT, \
  35. URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, URL_ADMIN_USER_GROUP, URL_ADMIN_REALM_ROLES, URL_ADMIN_GROUP_CHILD, \
  36. URL_ADMIN_USER_CONSENTS, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_CLIENT, URL_ADMIN_USER, URL_ADMIN_CLIENT_ROLE, \
  37. URL_ADMIN_USER_GROUPS, URL_ADMIN_CLIENTS, URL_ADMIN_FLOWS_EXECUTIONS, URL_ADMIN_GROUPS, URL_ADMIN_USER_CLIENT_ROLES, \
  38. URL_ADMIN_REALMS, URL_ADMIN_USERS_COUNT, URL_ADMIN_FLOWS, URL_ADMIN_GROUP, URL_ADMIN_CLIENT_AUTHZ_SETTINGS, \
  39. URL_ADMIN_GROUP_MEMBERS, URL_ADMIN_USER_STORAGE, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_IDPS, \
  40. URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, URL_ADMIN_USERS, URL_ADMIN_CLIENT_SCOPES, \
  41. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER, URL_ADMIN_CLIENT_SCOPE, URL_ADMIN_CLIENT_SECRETS, \
  42. URL_ADMIN_USER_REALM_ROLES, URL_ADMIN_REALM, URL_ADMIN_COMPONENTS, URL_ADMIN_COMPONENT, URL_ADMIN_KEYS, \
  43. URL_ADMIN_USER_FEDERATED_IDENTITY, URL_ADMIN_USER_FEDERATED_IDENTITIES
  44. class KeycloakAdmin:
  45. PAGE_SIZE = 100
  46. _server_url = None
  47. _username = None
  48. _password = None
  49. _realm_name = None
  50. _client_id = None
  51. _verify = None
  52. _client_secret_key = None
  53. _auto_refresh_token = None
  54. _connection = None
  55. _token = None
  56. _custom_headers = None
  57. _user_realm_name = None
  58. def __init__(self, server_url, username=None, password=None, realm_name='master', client_id='admin-cli', verify=True,
  59. client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None):
  60. """
  61. :param server_url: Keycloak server url
  62. :param username: admin username
  63. :param password: admin password
  64. :param realm_name: realm name
  65. :param client_id: client id
  66. :param verify: True if want check connection SSL
  67. :param client_secret_key: client secret key
  68. :param custom_headers: dict of custom header to pass to each HTML request
  69. :param user_realm_name: The realm name of the user, if different from realm_name
  70. :param auto_refresh_token: list of methods that allows automatic token refresh. ex: ['get', 'put', 'post', 'delete']
  71. """
  72. self.server_url = server_url
  73. self.username = username
  74. self.password = password
  75. self.realm_name = realm_name
  76. self.client_id = client_id
  77. self.verify = verify
  78. self.client_secret_key = client_secret_key
  79. self.auto_refresh_token = auto_refresh_token or []
  80. self.user_realm_name = user_realm_name
  81. self.custom_headers = custom_headers
  82. # Get token Admin
  83. self.get_token()
  84. @property
  85. def server_url(self):
  86. return self._server_url
  87. @server_url.setter
  88. def server_url(self, value):
  89. self._server_url = value
  90. @property
  91. def realm_name(self):
  92. return self._realm_name
  93. @realm_name.setter
  94. def realm_name(self, value):
  95. self._realm_name = value
  96. @property
  97. def connection(self):
  98. return self._connection
  99. @connection.setter
  100. def connection(self, value):
  101. self._connection = value
  102. @property
  103. def client_id(self):
  104. return self._client_id
  105. @client_id.setter
  106. def client_id(self, value):
  107. self._client_id = value
  108. @property
  109. def client_secret_key(self):
  110. return self._client_secret_key
  111. @client_secret_key.setter
  112. def client_secret_key(self, value):
  113. self._client_secret_key = value
  114. @property
  115. def verify(self):
  116. return self._verify
  117. @verify.setter
  118. def verify(self, value):
  119. self._verify = value
  120. @property
  121. def username(self):
  122. return self._username
  123. @username.setter
  124. def username(self, value):
  125. self._username = value
  126. @property
  127. def password(self):
  128. return self._password
  129. @password.setter
  130. def password(self, value):
  131. self._password = value
  132. @property
  133. def token(self):
  134. return self._token
  135. @token.setter
  136. def token(self, value):
  137. self._token = value
  138. @property
  139. def auto_refresh_token(self):
  140. return self._auto_refresh_token
  141. @property
  142. def user_realm_name(self):
  143. return self._user_realm_name
  144. @user_realm_name.setter
  145. def user_realm_name(self, value):
  146. self._user_realm_name = value
  147. @property
  148. def custom_headers(self):
  149. return self._custom_headers
  150. @custom_headers.setter
  151. def custom_headers(self, value):
  152. self._custom_headers = value
  153. @auto_refresh_token.setter
  154. def auto_refresh_token(self, value):
  155. allowed_methods = {'get', 'post', 'put', 'delete'}
  156. if not isinstance(value, Iterable):
  157. raise TypeError('Expected a list of strings among {allowed}'.format(allowed=allowed_methods))
  158. if not all(method in allowed_methods for method in value):
  159. raise TypeError('Unexpected method in auto_refresh_token, accepted methods are {allowed}'.format(allowed=allowed_methods))
  160. self._auto_refresh_token = value
  161. def __fetch_all(self, url, query=None):
  162. '''Wrapper function to paginate GET requests
  163. :param url: The url on which the query is executed
  164. :param query: Existing query parameters (optional)
  165. :return: Combined results of paginated queries
  166. '''
  167. results = []
  168. # initalize query if it was called with None
  169. if not query:
  170. query = {}
  171. page = 0
  172. query['max'] = self.PAGE_SIZE
  173. # fetch until we can
  174. while True:
  175. query['first'] = page*self.PAGE_SIZE
  176. partial_results = raise_error_from_response(
  177. self.raw_get(url, **query),
  178. KeycloakGetError)
  179. if not partial_results:
  180. break
  181. results.extend(partial_results)
  182. page += 1
  183. return results
  184. def __fetch_paginated(self, url, query=None):
  185. query = query or {}
  186. return raise_error_from_response(
  187. self.raw_get(url, **query),
  188. KeycloakGetError)
  189. def import_realm(self, payload):
  190. """
  191. Import a new realm from a RealmRepresentation. Realm name must be unique.
  192. RealmRepresentation
  193. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  194. :param payload: RealmRepresentation
  195. :return: RealmRepresentation
  196. """
  197. data_raw = self.raw_post(URL_ADMIN_REALMS,
  198. data=json.dumps(payload))
  199. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  200. def get_realms(self):
  201. """
  202. Lists all realms in Keycloak deployment
  203. :return: realms list
  204. """
  205. data_raw = self.raw_get(URL_ADMIN_REALMS)
  206. return raise_error_from_response(data_raw, KeycloakGetError)
  207. def create_realm(self, payload, skip_exists=False):
  208. """
  209. Create a realm
  210. RealmRepresentation:
  211. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  212. :param payload: RealmRepresentation
  213. :param skip_exists: Skip if Realm already exist.
  214. :return: Keycloak server response (RealmRepresentation)
  215. """
  216. data_raw = self.raw_post(URL_ADMIN_REALMS,
  217. data=json.dumps(payload))
  218. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  219. def update_realm(self, realm_name, payload):
  220. """
  221. Update a realm. This wil only update top level attributes and will ignore any user,
  222. role, or client information in the payload.
  223. RealmRepresentation:
  224. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
  225. :param realm_name: Realm name (not the realm id)
  226. :param payload: RealmRepresentation
  227. :return: Http response
  228. """
  229. params_path = {"realm-name": realm_name}
  230. data_raw = self.raw_put(URL_ADMIN_REALM.format(**params_path),
  231. data=json.dumps(payload))
  232. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  233. def delete_realm(self, realm_name):
  234. """
  235. Delete a realm
  236. :param realm_name: Realm name (not the realm id)
  237. :return: Http response
  238. """
  239. params_path = {"realm-name": realm_name}
  240. data_raw = self.raw_delete(URL_ADMIN_REALM.format(**params_path))
  241. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  242. def get_users(self, query=None):
  243. """
  244. Return a list of users, filtered according to query parameters
  245. UserRepresentation
  246. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  247. :param query: Query parameters (optional)
  248. :return: users list
  249. """
  250. query = query or {}
  251. params_path = {"realm-name": self.realm_name}
  252. url = URL_ADMIN_USERS.format(**params_path)
  253. if "first" in query or "max" in query:
  254. return self.__fetch_paginated(url, query)
  255. return self.__fetch_all(url, query)
  256. def get_idps(self):
  257. """
  258. Returns a list of ID Providers,
  259. IdentityProviderRepresentation
  260. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_identityproviderrepresentation
  261. :return: array IdentityProviderRepresentation
  262. """
  263. params_path = {"realm-name": self.realm_name}
  264. data_raw = self.raw_get(URL_ADMIN_IDPS.format(**params_path))
  265. return raise_error_from_response(data_raw, KeycloakGetError)
  266. def create_user(self, payload):
  267. """
  268. Create a new user. Username must be unique
  269. UserRepresentation
  270. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  271. :param payload: UserRepresentation
  272. :return: UserRepresentation
  273. """
  274. params_path = {"realm-name": self.realm_name}
  275. exists = self.get_user_id(username=payload['username'])
  276. if exists is not None:
  277. return str(exists)
  278. data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path),
  279. data=json.dumps(payload))
  280. raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  281. _last_slash_idx = data_raw.headers['Location'].rindex('/')
  282. return data_raw.headers['Location'][_last_slash_idx + 1:]
  283. def users_count(self):
  284. """
  285. User counter
  286. :return: counter
  287. """
  288. params_path = {"realm-name": self.realm_name}
  289. data_raw = self.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  290. return raise_error_from_response(data_raw, KeycloakGetError)
  291. def get_user_id(self, username):
  292. """
  293. Get internal keycloak user id from username
  294. This is required for further actions against this user.
  295. UserRepresentation
  296. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  297. :param username: id in UserRepresentation
  298. :return: user_id
  299. """
  300. users = self.get_users(query={"search": username})
  301. return next((user["id"] for user in users if user["username"] == username), None)
  302. def get_user(self, user_id):
  303. """
  304. Get representation of the user
  305. :param user_id: User id
  306. UserRepresentation
  307. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation
  308. :return: UserRepresentation
  309. """
  310. params_path = {"realm-name": self.realm_name, "id": user_id}
  311. data_raw = self.raw_get(URL_ADMIN_USER.format(**params_path))
  312. return raise_error_from_response(data_raw, KeycloakGetError)
  313. def get_user_groups(self, user_id):
  314. """
  315. Returns a list of groups of which the user is a member
  316. :param user_id: User id
  317. :return: user groups list
  318. """
  319. params_path = {"realm-name": self.realm_name, "id": user_id}
  320. data_raw = self.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  321. return raise_error_from_response(data_raw, KeycloakGetError)
  322. def update_user(self, user_id, payload):
  323. """
  324. Update the user
  325. :param user_id: User id
  326. :param payload: UserRepresentation
  327. :return: Http response
  328. """
  329. params_path = {"realm-name": self.realm_name, "id": user_id}
  330. data_raw = self.raw_put(URL_ADMIN_USER.format(**params_path),
  331. data=json.dumps(payload))
  332. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  333. def delete_user(self, user_id):
  334. """
  335. Delete the user
  336. :param user_id: User id
  337. :return: Http response
  338. """
  339. params_path = {"realm-name": self.realm_name, "id": user_id}
  340. data_raw = self.raw_delete(URL_ADMIN_USER.format(**params_path))
  341. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  342. def set_user_password(self, user_id, password, temporary=True):
  343. """
  344. Set up a password for the user. If temporary is True, the user will have to reset
  345. the temporary password next time they log in.
  346. https://www.keycloak.org/docs-api/8.0/rest-api/#_users_resource
  347. https://www.keycloak.org/docs-api/8.0/rest-api/#_credentialrepresentation
  348. :param user_id: User id
  349. :param password: New password
  350. :param temporary: True if password is temporary
  351. :return:
  352. """
  353. payload = {"type": "password", "temporary": temporary, "value": password}
  354. params_path = {"realm-name": self.realm_name, "id": user_id}
  355. data_raw = self.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  356. data=json.dumps(payload))
  357. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  358. def consents_user(self, user_id):
  359. """
  360. Get consents granted by the user
  361. :param user_id: User id
  362. :return: consents
  363. """
  364. params_path = {"realm-name": self.realm_name, "id": user_id}
  365. data_raw = self.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  366. return raise_error_from_response(data_raw, KeycloakGetError)
  367. def get_user_social_logins(self, user_id):
  368. """
  369. Returns a list of federated identities/social logins of which the user has been associated with
  370. :param user_id: User id
  371. :return: federated identities list
  372. """
  373. params_path = {"realm-name": self.realm_name, "id": user_id}
  374. data_raw = self.raw_get(URL_ADMIN_USER_FEDERATED_IDENTITIES.format(**params_path))
  375. return raise_error_from_response(data_raw, KeycloakGetError)
  376. def add_user_social_login(self, user_id, provider_id, provider_userid, provider_username):
  377. """
  378. Add a federated identity / social login provider to the user
  379. :param user_id: User id
  380. :param provider_id: Social login provider id
  381. :param provider_userid: userid specified by the provider
  382. :param provider_username: username specified by the provider
  383. :return:
  384. """
  385. payload = {"identityProvider": provider_id, "userId": provider_userid, "userName": provider_username}
  386. params_path = {"realm-name": self.realm_name, "id": user_id, "provider": provider_id}
  387. data_raw = self.raw_post(URL_ADMIN_USER_FEDERATED_IDENTITY.format(**params_path), data=json.dumps(payload))
  388. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  389. """
  390. Send an update account email to the user. An email contains a
  391. link the user can click to perform a set of required actions.
  392. :param user_id: User id
  393. :param payload: A list of actions for the user to complete
  394. :param client_id: Client id (optional)
  395. :param lifespan: Number of seconds after which the generated token expires (optional)
  396. :param redirect_uri: The redirect uri (optional)
  397. :return:
  398. """
  399. params_path = {"realm-name": self.realm_name, "id": user_id}
  400. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  401. data_raw = self.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  402. data=payload, **params_query)
  403. return raise_error_from_response(data_raw, KeycloakGetError)
  404. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  405. """
  406. Send a update account email to the user An email contains a
  407. link the user can click to perform a set of required actions.
  408. :param user_id: User id
  409. :param client_id: Client id (optional)
  410. :param redirect_uri: Redirect uri (optional)
  411. :return:
  412. """
  413. params_path = {"realm-name": self.realm_name, "id": user_id}
  414. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  415. data_raw = self.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  416. data={}, **params_query)
  417. return raise_error_from_response(data_raw, KeycloakGetError)
  418. def get_sessions(self, user_id):
  419. """
  420. Get sessions associated with the user
  421. :param user_id: id of user
  422. UserSessionRepresentation
  423. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_usersessionrepresentation
  424. :return: UserSessionRepresentation
  425. """
  426. params_path = {"realm-name": self.realm_name, "id": user_id}
  427. data_raw = self.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  428. return raise_error_from_response(data_raw, KeycloakGetError)
  429. def get_server_info(self):
  430. """
  431. Get themes, social providers, auth providers, and event listeners available on this server
  432. ServerInfoRepresentation
  433. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_serverinforepresentation
  434. :return: ServerInfoRepresentation
  435. """
  436. data_raw = self.raw_get(URL_ADMIN_SERVER_INFO)
  437. return raise_error_from_response(data_raw, KeycloakGetError)
  438. def get_groups(self, query=None):
  439. """
  440. Returns a list of groups belonging to the realm
  441. GroupRepresentation
  442. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  443. :return: array GroupRepresentation
  444. """
  445. query = query or {}
  446. params_path = {"realm-name": self.realm_name}
  447. url = URL_ADMIN_USERS.format(**params_path)
  448. if "first" in query or "max" in query:
  449. return self.__fetch_paginated(url, query)
  450. return self.__fetch_all(url, query)
  451. def get_group(self, group_id):
  452. """
  453. Get group by id. Returns full group details
  454. GroupRepresentation
  455. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  456. :param group_id: The group id
  457. :return: Keycloak server response (GroupRepresentation)
  458. """
  459. params_path = {"realm-name": self.realm_name, "id": group_id}
  460. data_raw = self.raw_get(URL_ADMIN_GROUP.format(**params_path))
  461. return raise_error_from_response(data_raw, KeycloakGetError)
  462. def get_subgroups(self, group, path):
  463. """
  464. Utility function to iterate through nested group structures
  465. GroupRepresentation
  466. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  467. :param name: group (GroupRepresentation)
  468. :param path: group path (string)
  469. :return: Keycloak server response (GroupRepresentation)
  470. """
  471. for subgroup in group["subGroups"]:
  472. if subgroup['path'] == path:
  473. return subgroup
  474. elif subgroup["subGroups"]:
  475. for subgroup in group["subGroups"]:
  476. result = self.get_subgroups(subgroup, path)
  477. if result:
  478. return result
  479. # went through the tree without hits
  480. return None
  481. def get_group_members(self, group_id, **query):
  482. """
  483. Get members by group id. Returns group members
  484. GroupRepresentation
  485. https://www.keycloak.org/docs-api/8.0/rest-api/#_userrepresentation
  486. :param group_id: The group id
  487. :param query: Additional query parameters (see https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getmembers)
  488. :return: Keycloak server response (UserRepresentation)
  489. """
  490. params_path = {"realm-name": self.realm_name, "id": group_id}
  491. url = URL_ADMIN_USERS.format(**params_path)
  492. if "first" in query or "max" in query:
  493. return self.__fetch_paginated(url, query)
  494. return self.__fetch_all(url, query)
  495. def get_group_by_path(self, path, search_in_subgroups=False):
  496. """
  497. Get group id based on name or path.
  498. A straight name or path match with a top-level group will return first.
  499. Subgroups are traversed, the first to match path (or name with path) is returned.
  500. GroupRepresentation
  501. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  502. :param path: group path
  503. :param search_in_subgroups: True if want search in the subgroups
  504. :return: Keycloak server response (GroupRepresentation)
  505. """
  506. groups = self.get_groups()
  507. # TODO: Review this code is necessary
  508. for group in groups:
  509. if group['path'] == path:
  510. return group
  511. elif search_in_subgroups and group["subGroups"]:
  512. for group in group["subGroups"]:
  513. if group['path'] == path:
  514. return group
  515. res = self.get_subgroups(group, path)
  516. if res != None:
  517. return res
  518. return None
  519. def create_group(self, payload, parent=None, skip_exists=False):
  520. """
  521. Creates a group in the Realm
  522. :param payload: GroupRepresentation
  523. :param parent: parent group's id. Required to create a sub-group.
  524. :param skip_exists: If true then do not raise an error if it already exists
  525. GroupRepresentation
  526. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  527. :return: Http response
  528. """
  529. if parent is None:
  530. params_path = {"realm-name": self.realm_name}
  531. data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  532. data=json.dumps(payload))
  533. else:
  534. params_path = {"realm-name": self.realm_name, "id": parent, }
  535. data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  536. data=json.dumps(payload))
  537. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  538. def update_group(self, group_id, payload):
  539. """
  540. Update group, ignores subgroups.
  541. :param group_id: id of group
  542. :param payload: GroupRepresentation with updated information.
  543. GroupRepresentation
  544. https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation
  545. :return: Http response
  546. """
  547. params_path = {"realm-name": self.realm_name, "id": group_id}
  548. data_raw = self.raw_put(URL_ADMIN_GROUP.format(**params_path),
  549. data=json.dumps(payload))
  550. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  551. def group_set_permissions(self, group_id, enabled=True):
  552. """
  553. Enable/Disable permissions for a group. Cannot delete group if disabled
  554. :param group_id: id of group
  555. :param enabled: boolean
  556. :return: Keycloak server response
  557. """
  558. params_path = {"realm-name": self.realm_name, "id": group_id}
  559. data_raw = self.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  560. data=json.dumps({"enabled": enabled}))
  561. return raise_error_from_response(data_raw, KeycloakGetError)
  562. def group_user_add(self, user_id, group_id):
  563. """
  564. Add user to group (user_id and group_id)
  565. :param user_id: id of user
  566. :param group_id: id of group to add to
  567. :return: Keycloak server response
  568. """
  569. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  570. data_raw = self.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  571. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  572. def group_user_remove(self, user_id, group_id):
  573. """
  574. Remove user from group (user_id and group_id)
  575. :param user_id: id of user
  576. :param group_id: id of group to remove from
  577. :return: Keycloak server response
  578. """
  579. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  580. data_raw = self.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  581. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  582. def delete_group(self, group_id):
  583. """
  584. Deletes a group in the Realm
  585. :param group_id: id of group to delete
  586. :return: Keycloak server response
  587. """
  588. params_path = {"realm-name": self.realm_name, "id": group_id}
  589. data_raw = self.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  590. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  591. def get_clients(self):
  592. """
  593. Returns a list of clients belonging to the realm
  594. ClientRepresentation
  595. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  596. :return: Keycloak server response (ClientRepresentation)
  597. """
  598. params_path = {"realm-name": self.realm_name}
  599. data_raw = self.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  600. return raise_error_from_response(data_raw, KeycloakGetError)
  601. def get_client(self, client_id):
  602. """
  603. Get representation of the client
  604. ClientRepresentation
  605. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  606. :param client_id: id of client (not client-id)
  607. :return: Keycloak server response (ClientRepresentation)
  608. """
  609. params_path = {"realm-name": self.realm_name, "id": client_id}
  610. data_raw = self.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  611. return raise_error_from_response(data_raw, KeycloakGetError)
  612. def get_client_id(self, client_name):
  613. """
  614. Get internal keycloak client id from client-id.
  615. This is required for further actions against this client.
  616. :param client_name: name in ClientRepresentation
  617. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  618. :return: client_id (uuid as string)
  619. """
  620. clients = self.get_clients()
  621. for client in clients:
  622. if client_name == client.get('name') or client_name == client.get('clientId'):
  623. return client["id"]
  624. return None
  625. def get_client_authz_settings(self, client_id):
  626. """
  627. Get authorization json from client.
  628. :param client_id: id in ClientRepresentation
  629. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  630. :return: Keycloak server response
  631. """
  632. params_path = {"realm-name": self.realm_name, "id": client_id}
  633. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  634. return data_raw
  635. def get_client_authz_resources(self, client_id):
  636. """
  637. Get resources from client.
  638. :param client_id: id in ClientRepresentation
  639. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  640. :return: Keycloak server response
  641. """
  642. params_path = {"realm-name": self.realm_name, "id": client_id}
  643. data_raw = self.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  644. return data_raw
  645. def create_client(self, payload, skip_exists=False):
  646. """
  647. Create a client
  648. ClientRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  649. :param skip_exists: If true then do not raise an error if client already exists
  650. :param payload: ClientRepresentation
  651. :return: Keycloak server response (UserRepresentation)
  652. """
  653. params_path = {"realm-name": self.realm_name}
  654. data_raw = self.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  655. data=json.dumps(payload))
  656. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  657. def update_client(self, client_id, payload):
  658. """
  659. Update a client
  660. :param client_id: Client id
  661. :param payload: ClientRepresentation
  662. :return: Http response
  663. """
  664. params_path = {"realm-name": self.realm_name, "id": client_id}
  665. data_raw = self.raw_put(URL_ADMIN_CLIENT.format(**params_path),
  666. data=json.dumps(payload))
  667. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  668. def delete_client(self, client_id):
  669. """
  670. Get representation of the client
  671. ClientRepresentation
  672. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_clientrepresentation
  673. :param client_id: keycloak client id (not oauth client-id)
  674. :return: Keycloak server response (ClientRepresentation)
  675. """
  676. params_path = {"realm-name": self.realm_name, "id": client_id}
  677. data_raw = self.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  678. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  679. def get_realm_roles(self):
  680. """
  681. Get all roles for the realm or client
  682. RoleRepresentation
  683. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  684. :return: Keycloak server response (RoleRepresentation)
  685. """
  686. params_path = {"realm-name": self.realm_name}
  687. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  688. return raise_error_from_response(data_raw, KeycloakGetError)
  689. def get_client_roles(self, client_id):
  690. """
  691. Get all roles for the client
  692. :param client_id: id of client (not client-id)
  693. RoleRepresentation
  694. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  695. :return: Keycloak server response (RoleRepresentation)
  696. """
  697. params_path = {"realm-name": self.realm_name, "id": client_id}
  698. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  699. return raise_error_from_response(data_raw, KeycloakGetError)
  700. def get_client_role(self, client_id, role_name):
  701. """
  702. Get client role id by name
  703. This is required for further actions with this role.
  704. :param client_id: id of client (not client-id)
  705. :param role_name: roles name (not id!)
  706. RoleRepresentation
  707. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  708. :return: role_id
  709. """
  710. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  711. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  712. return raise_error_from_response(data_raw, KeycloakGetError)
  713. def get_client_role_id(self, client_id, role_name):
  714. """
  715. Warning: Deprecated
  716. Get client role id by name
  717. This is required for further actions with this role.
  718. :param client_id: id of client (not client-id)
  719. :param role_name: roles name (not id!)
  720. RoleRepresentation
  721. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  722. :return: role_id
  723. """
  724. role = self.get_client_role(client_id, role_name)
  725. return role.get("id")
  726. def create_client_role(self, client_role_id, payload, skip_exists=False):
  727. """
  728. Create a client role
  729. RoleRepresentation
  730. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  731. :param client_role_id: id of client (not client-id)
  732. :param payload: RoleRepresentation
  733. :param skip_exists: If true then do not raise an error if client role already exists
  734. :return: Keycloak server response (RoleRepresentation)
  735. """
  736. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  737. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  738. data=json.dumps(payload))
  739. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  740. def delete_client_role(self, client_role_id, role_name):
  741. """
  742. Delete a client role
  743. RoleRepresentation
  744. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  745. :param client_role_id: id of client (not client-id)
  746. :param role_name: roles name (not id!)
  747. """
  748. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  749. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  750. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  751. def assign_client_role(self, user_id, client_id, roles):
  752. """
  753. Assign a client role to a user
  754. :param user_id: id of user
  755. :param client_id: id of client (not client-id)
  756. :param roles: roles list or role (use RoleRepresentation)
  757. :return Keycloak server response
  758. """
  759. payload = roles if isinstance(roles, list) else [roles]
  760. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  761. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  762. data=json.dumps(payload))
  763. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  764. def create_realm_role(self, payload, skip_exists=False):
  765. """
  766. Create a new role for the realm or client
  767. :param payload: The role (use RoleRepresentation)
  768. :param skip_exists: If true then do not raise an error if realm role already exists
  769. :return Keycloak server response
  770. """
  771. params_path = {"realm-name": self.realm_name}
  772. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  773. data=json.dumps(payload))
  774. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  775. def update_realm_role(self, role_name, payload):
  776. """
  777. Update a role for the realm by name
  778. :param role_name: The name of the role to be updated
  779. :param payload: The role (use RoleRepresentation)
  780. :return Keycloak server response
  781. """
  782. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  783. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  784. data=json.dumps(payload))
  785. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  786. def delete_realm_role(self, role_name):
  787. """
  788. Delete a role for the realm by name
  789. :param payload: The role name {'role-name':'name-of-the-role'}
  790. :return Keycloak server response
  791. """
  792. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  793. data_raw = self.connection.raw_delete(
  794. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  795. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  796. def assign_realm_roles(self, user_id, client_id, roles):
  797. """
  798. Assign realm roles to a user
  799. :param user_id: id of user
  800. :param client_id: id of client containing role (not client-id)
  801. :param roles: roles list or role (use RoleRepresentation)
  802. :return Keycloak server response
  803. """
  804. payload = roles if isinstance(roles, list) else [roles]
  805. params_path = {"realm-name": self.realm_name, "id": user_id}
  806. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  807. data=json.dumps(payload))
  808. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  809. def assign_group_realm_roles(self, group_id, roles):
  810. """
  811. Assign realm roles to a group
  812. :param group_id: id of groupp
  813. :param roles: roles list or role (use GroupRoleRepresentation)
  814. :return Keycloak server response
  815. """
  816. payload = roles if isinstance(roles, list) else [roles]
  817. params_path = {"realm-name": self.realm_name, "id": group_id}
  818. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  819. data=json.dumps(payload))
  820. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  821. def delete_group_realm_roles(self, group_id, roles):
  822. """
  823. Delete realm roles of a group
  824. :param group_id: id of group
  825. :param roles: roles list or role (use GroupRoleRepresentation)
  826. :return Keycloak server response
  827. """
  828. payload = roles if isinstance(roles, list) else [roles]
  829. params_path = {"realm-name": self.realm_name, "id": group_id}
  830. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  831. data=json.dumps(payload))
  832. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  833. def get_group_realm_roles(self, group_id):
  834. """
  835. Get all realm roles for a group.
  836. :param user_id: id of the group
  837. :return: Keycloak server response (array RoleRepresentation)
  838. """
  839. params_path = {"realm-name": self.realm_name, "id": group_id}
  840. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  841. return raise_error_from_response(data_raw, KeycloakGetError)
  842. def assign_group_client_roles(self, group_id, client_id, roles):
  843. """
  844. Assign client roles to a group
  845. :param group_id: id of group
  846. :param client_id: id of client (not client-id)
  847. :param roles: roles list or role (use GroupRoleRepresentation)
  848. :return Keycloak server response
  849. """
  850. payload = roles if isinstance(roles, list) else [roles]
  851. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  852. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  853. data=json.dumps(payload))
  854. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  855. def delete_group_client_roles(self, group_id, client_id, roles):
  856. """
  857. Delete client roles of a group
  858. :param group_id: id of group
  859. :param client_id: id of client (not client-id)
  860. :param roles: roles list or role (use GroupRoleRepresentation)
  861. :return Keycloak server response
  862. """
  863. payload = roles if isinstance(roles, list) else [roles]
  864. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  865. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  866. return raise_error_from_response(data_raw, KeycloakGetError)
  867. def get_group_client_roles(self, group_id, client_id, roles):
  868. """
  869. Get client roles of a group
  870. :param group_id: id of group
  871. :param client_id: id of client (not client-id)
  872. :param roles: roles list or role (use GroupRoleRepresentation)
  873. :return Keycloak server response (array RoleRepresentation)
  874. """
  875. payload = roles if isinstance(roles, list) else [roles]
  876. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  877. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  878. data=json.dumps(payload))
  879. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  880. def get_client_roles_of_user(self, user_id, client_id):
  881. """
  882. Get all client roles for a user.
  883. :param user_id: id of user
  884. :param client_id: id of client (not client-id)
  885. :return: Keycloak server response (array RoleRepresentation)
  886. """
  887. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  888. def get_available_client_roles_of_user(self, user_id, client_id):
  889. """
  890. Get available client role-mappings for a user.
  891. :param user_id: id of user
  892. :param client_id: id of client (not client-id)
  893. :return: Keycloak server response (array RoleRepresentation)
  894. """
  895. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  896. def get_composite_client_roles_of_user(self, user_id, client_id):
  897. """
  898. Get composite client role-mappings for a user.
  899. :param user_id: id of user
  900. :param client_id: id of client (not client-id)
  901. :return: Keycloak server response (array RoleRepresentation)
  902. """
  903. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  904. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  905. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  906. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  907. return raise_error_from_response(data_raw, KeycloakGetError)
  908. def delete_client_roles_of_user(self, user_id, client_id, roles):
  909. """
  910. Delete client roles from a user.
  911. :param user_id: id of user
  912. :param client_id: id of client containing role (not client-id)
  913. :param roles: roles list or role to delete (use RoleRepresentation)
  914. :return: Keycloak server response
  915. """
  916. payload = roles if isinstance(roles, list) else [roles]
  917. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  918. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  919. data=json.dumps(payload))
  920. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  921. def get_authentication_flows(self):
  922. """
  923. Get authentication flows. Returns all flow details
  924. AuthenticationFlowRepresentation
  925. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  926. :return: Keycloak server response (AuthenticationFlowRepresentation)
  927. """
  928. params_path = {"realm-name": self.realm_name}
  929. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  930. return raise_error_from_response(data_raw, KeycloakGetError)
  931. def create_authentication_flow(self, payload, skip_exists=False):
  932. """
  933. Create a new authentication flow
  934. AuthenticationFlowRepresentation
  935. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  936. :param payload: AuthenticationFlowRepresentation
  937. :param skip_exists: If true then do not raise an error if authentication flow already exists
  938. :return: Keycloak server response (RoleRepresentation)
  939. """
  940. params_path = {"realm-name": self.realm_name}
  941. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  942. data=payload)
  943. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  944. def get_authentication_flow_executions(self, flow_alias):
  945. """
  946. Get authentication flow executions. Returns all execution steps
  947. :param flow_alias: the flow alias
  948. :return: Response(json)
  949. """
  950. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  951. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  952. return raise_error_from_response(data_raw, KeycloakGetError)
  953. def update_authentication_flow_executions(self, payload, flow_alias):
  954. """
  955. Update an authentication flow execution
  956. AuthenticationExecutionInfoRepresentation
  957. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  958. :param payload: AuthenticationExecutionInfoRepresentation
  959. :param flow_alias: The flow alias
  960. :return: Keycloak server response
  961. """
  962. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  963. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  964. data=payload)
  965. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  966. def sync_users(self, storage_id, action):
  967. """
  968. Function to trigger user sync from provider
  969. :param storage_id: The id of the user storage provider
  970. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  971. :return:
  972. """
  973. data = {'action': action}
  974. params_query = {"action": action}
  975. params_path = {"realm-name": self.realm_name, "id": storage_id}
  976. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  977. data=json.dumps(data), **params_query)
  978. return raise_error_from_response(data_raw, KeycloakGetError)
  979. def get_client_scopes(self):
  980. """
  981. Get representation of the client scopes for the realm where we are connected to
  982. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  983. :return: Keycloak server response Array of (ClientScopeRepresentation)
  984. """
  985. params_path = {"realm-name": self.realm_name}
  986. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  987. return raise_error_from_response(data_raw, KeycloakGetError)
  988. def get_client_scope(self, client_scope_id):
  989. """
  990. Get representation of the client scopes for the realm where we are connected to
  991. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  992. :param client_scope_id: The id of the client scope
  993. :return: Keycloak server response (ClientScopeRepresentation)
  994. """
  995. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  996. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  997. return raise_error_from_response(data_raw, KeycloakGetError)
  998. def add_mapper_to_client_scope(self, client_scope_id, payload):
  999. """
  1000. Add a mapper to a client scope
  1001. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1002. :param client_scope_id: The id of the client scope
  1003. :param payload: ProtocolMapperRepresentation
  1004. :return: Keycloak server Response
  1005. """
  1006. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1007. data_raw = self.raw_post(
  1008. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1009. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1010. def generate_client_secrets(self, client_id):
  1011. """
  1012. Generate a new secret for the client
  1013. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1014. :param client_id: id of client (not client-id)
  1015. :return: Keycloak server response (ClientRepresentation)
  1016. """
  1017. params_path = {"realm-name": self.realm_name, "id": client_id}
  1018. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1019. return raise_error_from_response(data_raw, KeycloakGetError)
  1020. def get_client_secrets(self, client_id):
  1021. """
  1022. Get representation of the client secrets
  1023. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1024. :param client_id: id of client (not client-id)
  1025. :return: Keycloak server response (ClientRepresentation)
  1026. """
  1027. params_path = {"realm-name": self.realm_name, "id": client_id}
  1028. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1029. return raise_error_from_response(data_raw, KeycloakGetError)
  1030. def get_components(self, query=None):
  1031. """
  1032. Return a list of components, filtered according to query parameters
  1033. ComponentRepresentation
  1034. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1035. :param query: Query parameters (optional)
  1036. :return: components list
  1037. """
  1038. params_path = {"realm-name": self.realm_name}
  1039. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1040. data=None, **query)
  1041. return raise_error_from_response(data_raw, KeycloakGetError)
  1042. def create_component(self, payload):
  1043. """
  1044. Create a new component.
  1045. ComponentRepresentation
  1046. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1047. :param payload: ComponentRepresentation
  1048. :return: UserRepresentation
  1049. """
  1050. params_path = {"realm-name": self.realm_name}
  1051. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1052. data=json.dumps(payload))
  1053. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1054. def get_component(self, component_id):
  1055. """
  1056. Get representation of the component
  1057. :param component_id: Component id
  1058. ComponentRepresentation
  1059. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1060. :return: ComponentRepresentation
  1061. """
  1062. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1063. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1064. return raise_error_from_response(data_raw, KeycloakGetError)
  1065. def update_component(self, component_id, payload):
  1066. """
  1067. Update the component
  1068. :param component_id: Component id
  1069. :param payload: ComponentRepresentation
  1070. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1071. :return: Http response
  1072. """
  1073. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1074. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1075. data=json.dumps(payload))
  1076. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1077. def delete_component(self, component_id):
  1078. """
  1079. Delete the component
  1080. :param component_id: Component id
  1081. :return: Http response
  1082. """
  1083. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1084. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1085. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1086. def get_keys(self):
  1087. """
  1088. Return a list of keys, filtered according to query parameters
  1089. KeysMetadataRepresentation
  1090. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1091. :return: keys list
  1092. """
  1093. params_path = {"realm-name": self.realm_name}
  1094. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1095. data=None)
  1096. return raise_error_from_response(data_raw, KeycloakGetError)
  1097. def raw_get(self, *args, **kwargs):
  1098. """
  1099. Calls connection.raw_get.
  1100. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1101. and try *get* once more.
  1102. """
  1103. r = self.connection.raw_get(*args, **kwargs)
  1104. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1105. self.refresh_token()
  1106. return self.connection.raw_get(*args, **kwargs)
  1107. return r
  1108. def raw_post(self, *args, **kwargs):
  1109. """
  1110. Calls connection.raw_post.
  1111. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1112. and try *post* once more.
  1113. """
  1114. r = self.connection.raw_post(*args, **kwargs)
  1115. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1116. self.refresh_token()
  1117. return self.connection.raw_post(*args, **kwargs)
  1118. return r
  1119. def raw_put(self, *args, **kwargs):
  1120. """
  1121. Calls connection.raw_put.
  1122. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1123. and try *put* once more.
  1124. """
  1125. r = self.connection.raw_put(*args, **kwargs)
  1126. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1127. self.refresh_token()
  1128. return self.connection.raw_put(*args, **kwargs)
  1129. return r
  1130. def raw_delete(self, *args, **kwargs):
  1131. """
  1132. Calls connection.raw_delete.
  1133. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1134. and try *delete* once more.
  1135. """
  1136. r = self.connection.raw_delete(*args, **kwargs)
  1137. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1138. self.refresh_token()
  1139. return self.connection.raw_delete(*args, **kwargs)
  1140. return r
  1141. def get_token(self):
  1142. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1143. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1144. client_secret_key=self.client_secret_key,
  1145. custom_headers=self.custom_headers)
  1146. grant_type = ["password"]
  1147. if self.client_secret_key:
  1148. grant_type = ["client_credentials"]
  1149. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1150. headers = {
  1151. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1152. 'Content-Type': 'application/json'
  1153. }
  1154. if self.custom_headers is not None:
  1155. # merge custom headers to main headers
  1156. headers.update(self.custom_headers)
  1157. self._connection = ConnectionManager(base_url=self.server_url,
  1158. headers=headers,
  1159. timeout=60,
  1160. verify=self.verify)
  1161. def refresh_token(self):
  1162. refresh_token = self.token.get('refresh_token')
  1163. try:
  1164. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1165. except KeycloakGetError as e:
  1166. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1167. b'Token is not active' in e.response_body):
  1168. self.get_token()
  1169. else:
  1170. raise
  1171. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))