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.

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