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.

1882 lines
74 KiB

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