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.

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