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.

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