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.

1707 lines
66 KiB

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