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.

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