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.

1880 lines
74 KiB

7 years ago
6 years ago
6 years ago
4 years ago
6 years ago
7 years ago
6 years ago
4 years ago
4 years ago
4 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
5 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from builtins import isinstance
  27. from typing import 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 get_realm_roles_of_user(self, user_id):
  936. """
  937. Get all realm roles for a user.
  938. :param user_id: id of user
  939. :return: Keycloak server response (array RoleRepresentation)
  940. """
  941. params_path = {"realm-name": self.realm_name, "id": user_id}
  942. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  943. return raise_error_from_response(data_raw, KeycloakGetError)
  944. def assign_group_realm_roles(self, group_id, roles):
  945. """
  946. Assign realm roles to a group
  947. :param group_id: id of groupp
  948. :param roles: roles list or role (use GroupRoleRepresentation)
  949. :return Keycloak server response
  950. """
  951. payload = roles if isinstance(roles, list) else [roles]
  952. params_path = {"realm-name": self.realm_name, "id": group_id}
  953. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  954. data=json.dumps(payload))
  955. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  956. def delete_group_realm_roles(self, group_id, roles):
  957. """
  958. Delete realm roles of a group
  959. :param group_id: id of group
  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_delete(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 get_group_realm_roles(self, group_id):
  969. """
  970. Get all realm roles for a group.
  971. :param user_id: id of the group
  972. :return: Keycloak server response (array RoleRepresentation)
  973. """
  974. params_path = {"realm-name": self.realm_name, "id": group_id}
  975. data_raw = self.raw_get(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path))
  976. return raise_error_from_response(data_raw, KeycloakGetError)
  977. def assign_group_client_roles(self, group_id, client_id, roles):
  978. """
  979. Assign client roles to a group
  980. :param group_id: id of group
  981. :param client_id: id of client (not client-id)
  982. :param roles: roles list or role (use GroupRoleRepresentation)
  983. :return Keycloak server response
  984. """
  985. payload = roles if isinstance(roles, list) else [roles]
  986. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  987. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  988. data=json.dumps(payload))
  989. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  990. def get_group_client_roles(self, group_id, client_id):
  991. """
  992. Get client roles of a group
  993. :param group_id: id of group
  994. :param client_id: id of client (not client-id)
  995. :return Keycloak server response
  996. """
  997. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  998. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  999. return raise_error_from_response(data_raw, KeycloakGetError)
  1000. def delete_group_client_roles(self, group_id, client_id, roles):
  1001. """
  1002. Delete client roles of a group
  1003. :param group_id: id of group
  1004. :param client_id: id of client (not client-id)
  1005. :param roles: roles list or role (use GroupRoleRepresentation)
  1006. :return Keycloak server response (array RoleRepresentation)
  1007. """
  1008. payload = roles if isinstance(roles, list) else [roles]
  1009. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  1010. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  1011. data=json.dumps(payload))
  1012. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1013. def get_client_roles_of_user(self, user_id, client_id):
  1014. """
  1015. Get all client roles for a user.
  1016. :param user_id: id of user
  1017. :param client_id: id of client (not client-id)
  1018. :return: Keycloak server response (array RoleRepresentation)
  1019. """
  1020. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  1021. def get_available_client_roles_of_user(self, user_id, client_id):
  1022. """
  1023. Get available client role-mappings for a user.
  1024. :param user_id: id of user
  1025. :param client_id: id of client (not client-id)
  1026. :return: Keycloak server response (array RoleRepresentation)
  1027. """
  1028. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1029. def get_composite_client_roles_of_user(self, user_id, client_id):
  1030. """
  1031. Get composite client role-mappings for a user.
  1032. :param user_id: id of user
  1033. :param client_id: id of client (not client-id)
  1034. :return: Keycloak server response (array RoleRepresentation)
  1035. """
  1036. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1037. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1038. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1039. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1040. return raise_error_from_response(data_raw, KeycloakGetError)
  1041. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1042. """
  1043. Delete client roles from a user.
  1044. :param user_id: id of user
  1045. :param client_id: id of client containing role (not client-id)
  1046. :param roles: roles list or role to delete (use RoleRepresentation)
  1047. :return: Keycloak server response
  1048. """
  1049. payload = roles if isinstance(roles, list) else [roles]
  1050. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1051. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1052. data=json.dumps(payload))
  1053. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1054. def get_authentication_flows(self):
  1055. """
  1056. Get authentication flows. Returns all flow details
  1057. AuthenticationFlowRepresentation
  1058. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1059. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1060. """
  1061. params_path = {"realm-name": self.realm_name}
  1062. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1063. return raise_error_from_response(data_raw, KeycloakGetError)
  1064. def get_authentication_flow_for_id(self, flow_id):
  1065. """
  1066. Get one authentication flow by it's id/alias. Returns all flow details
  1067. AuthenticationFlowRepresentation
  1068. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1069. :param flow_id: the id of a flow NOT it's alias
  1070. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1071. """
  1072. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1073. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1074. return raise_error_from_response(data_raw, KeycloakGetError)
  1075. def create_authentication_flow(self, payload, skip_exists=False):
  1076. """
  1077. Create a new authentication flow
  1078. AuthenticationFlowRepresentation
  1079. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1080. :param payload: AuthenticationFlowRepresentation
  1081. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1082. :return: Keycloak server response (RoleRepresentation)
  1083. """
  1084. params_path = {"realm-name": self.realm_name}
  1085. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1086. data=json.dumps(payload))
  1087. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1088. def copy_authentication_flow(self, payload, flow_alias):
  1089. """
  1090. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1091. :param payload: JSON containing 'newName' attribute
  1092. :param flow_alias: the flow alias
  1093. :return: Keycloak server response (RoleRepresentation)
  1094. """
  1095. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1096. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1097. data=json.dumps(payload))
  1098. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1099. def get_authentication_flow_executions(self, flow_alias):
  1100. """
  1101. Get authentication flow executions. Returns all execution steps
  1102. :param flow_alias: the flow alias
  1103. :return: Response(json)
  1104. """
  1105. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1106. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1107. return raise_error_from_response(data_raw, KeycloakGetError)
  1108. def update_authentication_flow_executions(self, payload, flow_alias):
  1109. """
  1110. Update an authentication flow execution
  1111. AuthenticationExecutionInfoRepresentation
  1112. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1113. :param payload: AuthenticationExecutionInfoRepresentation
  1114. :param flow_alias: The flow alias
  1115. :return: Keycloak server response
  1116. """
  1117. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1118. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1119. data=json.dumps(payload))
  1120. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1121. def create_authentication_flow_execution(self, payload, flow_alias):
  1122. """
  1123. Create an authentication flow execution
  1124. AuthenticationExecutionInfoRepresentation
  1125. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1126. :param payload: AuthenticationExecutionInfoRepresentation
  1127. :param flow_alias: The flow alias
  1128. :return: Keycloak server response
  1129. """
  1130. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1131. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1132. data=json.dumps(payload))
  1133. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1134. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1135. """
  1136. Create a new sub authentication flow for a given authentication flow
  1137. AuthenticationFlowRepresentation
  1138. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1139. :param payload: AuthenticationFlowRepresentation
  1140. :param flow_alias: The flow alias
  1141. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1142. :return: Keycloak server response (RoleRepresentation)
  1143. """
  1144. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1145. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1146. data=json.dumps(payload))
  1147. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1148. def get_authenticator_config(self, config_id):
  1149. """
  1150. Get authenticator configuration. Returns all configuration details.
  1151. :param config_id: Authenticator config id
  1152. :return: Response(json)
  1153. """
  1154. params_path = {"realm-name": self.realm_name, "id": config_id}
  1155. data_raw = self.raw_get(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1156. return raise_error_from_response(data_raw, KeycloakGetError)
  1157. def update_authenticator_config(self, payload, config_id):
  1158. """
  1159. Update an authenticator configuration.
  1160. AuthenticatorConfigRepresentation
  1161. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticatorconfigrepresentation
  1162. :param payload: AuthenticatorConfigRepresentation
  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_put(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path),
  1168. data=json.dumps(payload))
  1169. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1170. def delete_authenticator_config(self, config_id):
  1171. """
  1172. Delete a authenticator configuration.
  1173. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource
  1174. :param config_id: Authenticator config id
  1175. :return: Keycloak server Response
  1176. """
  1177. params_path = {"realm-name": self.realm_name, "id": config_id}
  1178. data_raw = self.raw_delete(URL_ADMIN_AUTHENTICATOR_CONFIG.format(**params_path))
  1179. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1180. def sync_users(self, storage_id, action):
  1181. """
  1182. Function to trigger user sync from provider
  1183. :param storage_id: The id of the user storage provider
  1184. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1185. :return:
  1186. """
  1187. data = {'action': action}
  1188. params_query = {"action": action}
  1189. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1190. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1191. data=json.dumps(data), **params_query)
  1192. return raise_error_from_response(data_raw, KeycloakGetError)
  1193. def get_client_scopes(self):
  1194. """
  1195. Get representation of the client scopes for the realm where we are connected to
  1196. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1197. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1198. """
  1199. params_path = {"realm-name": self.realm_name}
  1200. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1201. return raise_error_from_response(data_raw, KeycloakGetError)
  1202. def get_client_scope(self, client_scope_id):
  1203. """
  1204. Get representation of the client scopes for the realm where we are connected to
  1205. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1206. :param client_scope_id: The id of the client scope
  1207. :return: Keycloak server response (ClientScopeRepresentation)
  1208. """
  1209. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1210. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1211. return raise_error_from_response(data_raw, KeycloakGetError)
  1212. def create_client_scope(self, payload, skip_exists=False):
  1213. """
  1214. Create a client scope
  1215. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1216. :param payload: ClientScopeRepresentation
  1217. :param skip_exists: If true then do not raise an error if client scope already exists
  1218. :return: Keycloak server response (ClientScopeRepresentation)
  1219. """
  1220. params_path = {"realm-name": self.realm_name}
  1221. data_raw = self.raw_post(URL_ADMIN_CLIENT_SCOPES.format(**params_path),
  1222. data=json.dumps(payload))
  1223. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1224. def update_client_scope(self, client_scope_id, payload):
  1225. """
  1226. Update a client scope
  1227. ClientScopeRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_client_scopes_resource
  1228. :param client_scope_id: The id of the client scope
  1229. :param payload: ClientScopeRepresentation
  1230. :return: Keycloak server response (ClientScopeRepresentation)
  1231. """
  1232. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1233. data_raw = self.raw_put(URL_ADMIN_CLIENT_SCOPE.format(**params_path),
  1234. data=json.dumps(payload))
  1235. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1236. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1237. """
  1238. Add a mapper to a client scope
  1239. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1240. :param client_scope_id: The id of the client scope
  1241. :param payload: ProtocolMapperRepresentation
  1242. :return: Keycloak server Response
  1243. """
  1244. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1245. data_raw = self.raw_post(
  1246. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1247. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1248. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1249. """
  1250. Delete a mapper from a client scope
  1251. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_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. "protocol-mapper-id": protocol_mppaer_id}
  1258. data_raw = self.raw_delete(
  1259. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1260. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1261. def update_mapper_in_client_scope(self, client_scope_id, protocol_mapper_id, payload):
  1262. """
  1263. Update an existing protocol mapper in a client scope
  1264. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_protocol_mappers_resource
  1265. :param client_scope_id: The id of the client scope
  1266. :param protocol_mapper_id: The id of the protocol mapper which exists in the client scope
  1267. and should to be updated
  1268. :param payload: ProtocolMapperRepresentation
  1269. :return: Keycloak server Response
  1270. """
  1271. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1272. "protocol-mapper-id": protocol_mapper_id}
  1273. data_raw = self.raw_put(
  1274. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path), data=json.dumps(payload))
  1275. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1276. def add_mapper_to_client(self, client_id, payload):
  1277. """
  1278. Add a mapper to a client
  1279. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1280. :param client_id: The id of the client
  1281. :param payload: ProtocolMapperRepresentation
  1282. :return: Keycloak server Response
  1283. """
  1284. params_path = {"realm-name": self.realm_name, "id": client_id}
  1285. data_raw = self.raw_post(
  1286. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1287. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1288. def generate_client_secrets(self, client_id):
  1289. """
  1290. Generate a new secret for the client
  1291. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1292. :param client_id: id of client (not client-id)
  1293. :return: Keycloak server response (ClientRepresentation)
  1294. """
  1295. params_path = {"realm-name": self.realm_name, "id": client_id}
  1296. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1297. return raise_error_from_response(data_raw, KeycloakGetError)
  1298. def get_client_secrets(self, client_id):
  1299. """
  1300. Get representation of the client secrets
  1301. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1302. :param client_id: id of client (not client-id)
  1303. :return: Keycloak server response (ClientRepresentation)
  1304. """
  1305. params_path = {"realm-name": self.realm_name, "id": client_id}
  1306. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1307. return raise_error_from_response(data_raw, KeycloakGetError)
  1308. def get_components(self, query=None):
  1309. """
  1310. Return a list of components, filtered according to query parameters
  1311. ComponentRepresentation
  1312. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1313. :param query: Query parameters (optional)
  1314. :return: components list
  1315. """
  1316. params_path = {"realm-name": self.realm_name}
  1317. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1318. data=None, **query)
  1319. return raise_error_from_response(data_raw, KeycloakGetError)
  1320. def create_component(self, payload):
  1321. """
  1322. Create a new component.
  1323. ComponentRepresentation
  1324. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1325. :param payload: ComponentRepresentation
  1326. :return: UserRepresentation
  1327. """
  1328. params_path = {"realm-name": self.realm_name}
  1329. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1330. data=json.dumps(payload))
  1331. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1332. def get_component(self, component_id):
  1333. """
  1334. Get representation of the component
  1335. :param component_id: Component id
  1336. ComponentRepresentation
  1337. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1338. :return: ComponentRepresentation
  1339. """
  1340. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1341. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1342. return raise_error_from_response(data_raw, KeycloakGetError)
  1343. def update_component(self, component_id, payload):
  1344. """
  1345. Update the component
  1346. :param component_id: Component id
  1347. :param payload: ComponentRepresentation
  1348. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1349. :return: Http response
  1350. """
  1351. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1352. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1353. data=json.dumps(payload))
  1354. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1355. def delete_component(self, component_id):
  1356. """
  1357. Delete the component
  1358. :param component_id: Component id
  1359. :return: Http response
  1360. """
  1361. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1362. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1363. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1364. def get_keys(self):
  1365. """
  1366. Return a list of keys, filtered according to query parameters
  1367. KeysMetadataRepresentation
  1368. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1369. :return: keys list
  1370. """
  1371. params_path = {"realm-name": self.realm_name}
  1372. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1373. data=None)
  1374. return raise_error_from_response(data_raw, KeycloakGetError)
  1375. def get_events(self, query=None):
  1376. """
  1377. Return a list of events, filtered according to query parameters
  1378. EventRepresentation array
  1379. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_eventrepresentation
  1380. :return: events list
  1381. """
  1382. params_path = {"realm-name": self.realm_name}
  1383. data_raw = self.raw_get(URL_ADMIN_EVENTS.format(**params_path),
  1384. data=None, **query)
  1385. return raise_error_from_response(data_raw, KeycloakGetError)
  1386. def raw_get(self, *args, **kwargs):
  1387. """
  1388. Calls connection.raw_get.
  1389. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1390. and try *get* once more.
  1391. """
  1392. r = self.connection.raw_get(*args, **kwargs)
  1393. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1394. self.refresh_token()
  1395. return self.connection.raw_get(*args, **kwargs)
  1396. return r
  1397. def raw_post(self, *args, **kwargs):
  1398. """
  1399. Calls connection.raw_post.
  1400. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1401. and try *post* once more.
  1402. """
  1403. r = self.connection.raw_post(*args, **kwargs)
  1404. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1405. self.refresh_token()
  1406. return self.connection.raw_post(*args, **kwargs)
  1407. return r
  1408. def raw_put(self, *args, **kwargs):
  1409. """
  1410. Calls connection.raw_put.
  1411. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1412. and try *put* once more.
  1413. """
  1414. r = self.connection.raw_put(*args, **kwargs)
  1415. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1416. self.refresh_token()
  1417. return self.connection.raw_put(*args, **kwargs)
  1418. return r
  1419. def raw_delete(self, *args, **kwargs):
  1420. """
  1421. Calls connection.raw_delete.
  1422. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1423. and try *delete* once more.
  1424. """
  1425. r = self.connection.raw_delete(*args, **kwargs)
  1426. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1427. self.refresh_token()
  1428. return self.connection.raw_delete(*args, **kwargs)
  1429. return r
  1430. def get_token(self):
  1431. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1432. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1433. client_secret_key=self.client_secret_key,
  1434. custom_headers=self.custom_headers)
  1435. grant_type = ["password"]
  1436. if self.client_secret_key:
  1437. grant_type = ["client_credentials"]
  1438. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1439. headers = {
  1440. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1441. 'Content-Type': 'application/json'
  1442. }
  1443. if self.custom_headers is not None:
  1444. # merge custom headers to main headers
  1445. headers.update(self.custom_headers)
  1446. self._connection = ConnectionManager(base_url=self.server_url,
  1447. headers=headers,
  1448. timeout=60,
  1449. verify=self.verify)
  1450. def refresh_token(self):
  1451. refresh_token = self.token.get('refresh_token')
  1452. try:
  1453. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1454. except KeycloakGetError as e:
  1455. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1456. b'Token is not active' in e.response_body):
  1457. self.get_token()
  1458. else:
  1459. raise
  1460. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))
  1461. def get_client_all_sessions(self, client_id):
  1462. """
  1463. Get sessions associated with the client
  1464. :param client_id: id of client
  1465. UserSessionRepresentation
  1466. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  1467. :return: UserSessionRepresentation
  1468. """
  1469. params_path = {"realm-name": self.realm_name, "id": client_id}
  1470. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ALL_SESSIONS.format(**params_path))
  1471. return raise_error_from_response(data_raw, KeycloakGetError)