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.

1729 lines
67 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, URL_ADMIN_CLIENT_ROLE_MEMBERS, \
  46. URL_ADMIN_REALM_ROLES_MEMBERS, 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_realm_role_members(self, role_name, **query):
  723. """
  724. Get role members of realm by role name.
  725. :param role_name: Name of the role.
  726. :param query: Additional Query parameters (see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_roles_resource)
  727. :return: Keycloak Server Response (UserRepresentation)
  728. """
  729. params_path = {"realm-name": self.realm_name, "role-name":role_name}
  730. return self.__fetch_all(URL_ADMIN_REALM_ROLES_MEMBERS.format(**params_path), query)
  731. def get_client_roles(self, client_id):
  732. """
  733. Get all roles for the client
  734. :param client_id: id of client (not client-id)
  735. RoleRepresentation
  736. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  737. :return: Keycloak server response (RoleRepresentation)
  738. """
  739. params_path = {"realm-name": self.realm_name, "id": client_id}
  740. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  741. return raise_error_from_response(data_raw, KeycloakGetError)
  742. def get_client_role(self, client_id, role_name):
  743. """
  744. Get client role id by name
  745. This is required for further actions with this role.
  746. :param client_id: id of client (not client-id)
  747. :param role_name: roles name (not id!)
  748. RoleRepresentation
  749. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  750. :return: role_id
  751. """
  752. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  753. data_raw = self.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  754. return raise_error_from_response(data_raw, KeycloakGetError)
  755. def get_client_role_id(self, client_id, role_name):
  756. """
  757. Warning: Deprecated
  758. Get client role id by name
  759. This is required for further actions with this role.
  760. :param client_id: id of client (not client-id)
  761. :param role_name: roles name (not id!)
  762. RoleRepresentation
  763. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  764. :return: role_id
  765. """
  766. role = self.get_client_role(client_id, role_name)
  767. return role.get("id")
  768. def create_client_role(self, client_role_id, payload, skip_exists=False):
  769. """
  770. Create a client role
  771. RoleRepresentation
  772. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  773. :param client_role_id: id of client (not client-id)
  774. :param payload: RoleRepresentation
  775. :param skip_exists: If true then do not raise an error if client role already exists
  776. :return: Keycloak server response (RoleRepresentation)
  777. """
  778. params_path = {"realm-name": self.realm_name, "id": client_role_id}
  779. data_raw = self.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  780. data=json.dumps(payload))
  781. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  782. def delete_client_role(self, client_role_id, role_name):
  783. """
  784. Delete a client role
  785. RoleRepresentation
  786. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  787. :param client_role_id: id of client (not client-id)
  788. :param role_name: roles name (not id!)
  789. """
  790. params_path = {"realm-name": self.realm_name, "id": client_role_id, "role-name": role_name}
  791. data_raw = self.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  792. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  793. def assign_client_role(self, user_id, client_id, roles):
  794. """
  795. Assign a client role to a user
  796. :param user_id: id of user
  797. :param client_id: id of client (not client-id)
  798. :param roles: roles list or role (use RoleRepresentation)
  799. :return Keycloak server response
  800. """
  801. payload = roles if isinstance(roles, list) else [roles]
  802. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  803. data_raw = self.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  804. data=json.dumps(payload))
  805. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  806. def get_client_role_members(self, client_id, role_name, **query):
  807. """
  808. Get members by client role .
  809. :param client_id: The client id
  810. :param role_name: the name of role to be queried.
  811. :param query: Additional query parameters ( see https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_clients_resource)
  812. :return: Keycloak server response (UserRepresentation)
  813. """
  814. params_path = {"realm-name": self.realm_name, "id":client_id, "role-name":role_name}
  815. return self.__fetch_all(URL_ADMIN_CLIENT_ROLE_MEMBERS.format(**params_path) , query)
  816. def create_realm_role(self, payload, skip_exists=False):
  817. """
  818. Create a new role for the realm or client
  819. :param payload: The role (use RoleRepresentation)
  820. :param skip_exists: If true then do not raise an error if realm role already exists
  821. :return Keycloak server response
  822. """
  823. params_path = {"realm-name": self.realm_name}
  824. data_raw = self.raw_post(URL_ADMIN_REALM_ROLES.format(**params_path),
  825. data=json.dumps(payload))
  826. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  827. def get_realm_role(self, role_name):
  828. """
  829. Get realm role by role name
  830. :param role_name: role's name, not id!
  831. RoleRepresentation
  832. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_rolerepresentation
  833. :return: role_id
  834. """
  835. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  836. data_raw = self.raw_get(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  837. return raise_error_from_response(data_raw, KeycloakGetError)
  838. def update_realm_role(self, role_name, payload):
  839. """
  840. Update a role for the realm by name
  841. :param role_name: The name of the role to be updated
  842. :param payload: The role (use RoleRepresentation)
  843. :return Keycloak server response
  844. """
  845. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  846. data_raw = self.connection.raw_put(URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path),
  847. data=json.dumps(payload))
  848. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  849. def delete_realm_role(self, role_name):
  850. """
  851. Delete a role for the realm by name
  852. :param payload: The role name {'role-name':'name-of-the-role'}
  853. :return Keycloak server response
  854. """
  855. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  856. data_raw = self.connection.raw_delete(
  857. URL_ADMIN_REALM_ROLES_ROLE_BY_NAME.format(**params_path))
  858. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  859. def add_composite_realm_roles_to_role(self, role_name, roles):
  860. """
  861. Add composite roles to the role
  862. :param role_name: The name of the role
  863. :param roles: roles list or role (use RoleRepresentation) to be updated
  864. :return Keycloak server response
  865. """
  866. payload = roles if isinstance(roles, list) else [roles]
  867. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  868. data_raw = self.raw_post(
  869. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  870. data=json.dumps(payload))
  871. return raise_error_from_response(data_raw, KeycloakGetError,
  872. expected_codes=[204])
  873. def remove_composite_realm_roles_to_role(self, role_name, roles):
  874. """
  875. Remove composite roles from the role
  876. :param role_name: The name of the role
  877. :param roles: roles list or role (use RoleRepresentation) to be removed
  878. :return Keycloak server response
  879. """
  880. payload = roles if isinstance(roles, list) else [roles]
  881. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  882. data_raw = self.raw_delete(
  883. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path),
  884. data=json.dumps(payload))
  885. return raise_error_from_response(data_raw, KeycloakGetError,
  886. expected_codes=[204])
  887. def get_composite_realm_roles_of_role(self, role_name):
  888. """
  889. Get composite roles of the role
  890. :param role_name: The name of the role
  891. :return Keycloak server response (array RoleRepresentation)
  892. """
  893. params_path = {"realm-name": self.realm_name, "role-name": role_name}
  894. data_raw = self.raw_get(
  895. URL_ADMIN_REALM_ROLES_COMPOSITE_REALM_ROLE.format(**params_path))
  896. return raise_error_from_response(data_raw, KeycloakGetError)
  897. def assign_realm_roles(self, user_id, client_id, roles):
  898. """
  899. Assign realm roles to a user
  900. :param user_id: id of user
  901. :param client_id: id of client containing role (not client-id)
  902. :param roles: roles list or role (use RoleRepresentation)
  903. :return Keycloak server response
  904. """
  905. payload = roles if isinstance(roles, list) else [roles]
  906. params_path = {"realm-name": self.realm_name, "id": user_id}
  907. data_raw = self.raw_post(URL_ADMIN_USER_REALM_ROLES.format(**params_path),
  908. data=json.dumps(payload))
  909. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  910. def get_realm_roles_of_user(self, user_id):
  911. """
  912. Get all realm roles for a user.
  913. :param user_id: id of user
  914. :return: Keycloak server response (array RoleRepresentation)
  915. """
  916. params_path = {"realm-name": self.realm_name, "id": user_id}
  917. data_raw = self.raw_get(URL_ADMIN_USER_REALM_ROLES.format(**params_path))
  918. return raise_error_from_response(data_raw, KeycloakGetError)
  919. def assign_group_realm_roles(self, group_id, roles):
  920. """
  921. Assign realm roles to a group
  922. :param group_id: id of groupp
  923. :param roles: roles list or role (use GroupRoleRepresentation)
  924. :return Keycloak server response
  925. """
  926. payload = roles if isinstance(roles, list) else [roles]
  927. params_path = {"realm-name": self.realm_name, "id": group_id}
  928. data_raw = self.raw_post(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  929. data=json.dumps(payload))
  930. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  931. def delete_group_realm_roles(self, group_id, roles):
  932. """
  933. Delete realm roles of a group
  934. :param group_id: id of group
  935. :param roles: roles list or role (use GroupRoleRepresentation)
  936. :return Keycloak server response
  937. """
  938. payload = roles if isinstance(roles, list) else [roles]
  939. params_path = {"realm-name": self.realm_name, "id": group_id}
  940. data_raw = self.raw_delete(URL_ADMIN_GROUPS_REALM_ROLES.format(**params_path),
  941. data=json.dumps(payload))
  942. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  943. def get_group_realm_roles(self, group_id):
  944. """
  945. Get all realm roles for a group.
  946. :param user_id: id of the group
  947. :return: Keycloak server response (array RoleRepresentation)
  948. """
  949. params_path = {"realm-name": self.realm_name, "id": group_id}
  950. data_raw = self.raw_get(URL_ADMIN_GET_GROUPS_REALM_ROLES.format(**params_path))
  951. return raise_error_from_response(data_raw, KeycloakGetError)
  952. def assign_group_client_roles(self, group_id, client_id, roles):
  953. """
  954. Assign client roles to a group
  955. :param group_id: id of group
  956. :param client_id: id of client (not client-id)
  957. :param roles: roles list or role (use GroupRoleRepresentation)
  958. :return Keycloak server response
  959. """
  960. payload = roles if isinstance(roles, list) else [roles]
  961. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  962. data_raw = self.raw_post(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  963. data=json.dumps(payload))
  964. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  965. def get_group_client_roles(self, group_id, client_id):
  966. """
  967. Get client roles of a group
  968. :param group_id: id of group
  969. :param client_id: id of client (not client-id)
  970. :return Keycloak server response
  971. """
  972. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  973. data_raw = self.raw_get(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path))
  974. return raise_error_from_response(data_raw, KeycloakGetError)
  975. def delete_group_client_roles(self, group_id, client_id, roles):
  976. """
  977. Delete client roles of a group
  978. :param group_id: id of group
  979. :param client_id: id of client (not client-id)
  980. :param roles: roles list or role (use GroupRoleRepresentation)
  981. :return Keycloak server response (array RoleRepresentation)
  982. """
  983. payload = roles if isinstance(roles, list) else [roles]
  984. params_path = {"realm-name": self.realm_name, "id": group_id, "client-id": client_id}
  985. data_raw = self.raw_delete(URL_ADMIN_GROUPS_CLIENT_ROLES.format(**params_path),
  986. data=json.dumps(payload))
  987. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  988. def get_client_roles_of_user(self, user_id, client_id):
  989. """
  990. Get all client roles for a user.
  991. :param user_id: id of user
  992. :param client_id: id of client (not client-id)
  993. :return: Keycloak server response (array RoleRepresentation)
  994. """
  995. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  996. def get_available_client_roles_of_user(self, user_id, client_id):
  997. """
  998. Get available client role-mappings for a user.
  999. :param user_id: id of user
  1000. :param client_id: id of client (not client-id)
  1001. :return: Keycloak server response (array RoleRepresentation)
  1002. """
  1003. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  1004. def get_composite_client_roles_of_user(self, user_id, client_id):
  1005. """
  1006. Get composite client role-mappings for a user.
  1007. :param user_id: id of user
  1008. :param client_id: id of client (not client-id)
  1009. :return: Keycloak server response (array RoleRepresentation)
  1010. """
  1011. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  1012. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  1013. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1014. data_raw = self.raw_get(client_level_role_mapping_url.format(**params_path))
  1015. return raise_error_from_response(data_raw, KeycloakGetError)
  1016. def delete_client_roles_of_user(self, user_id, client_id, roles):
  1017. """
  1018. Delete client roles from a user.
  1019. :param user_id: id of user
  1020. :param client_id: id of client containing role (not client-id)
  1021. :param roles: roles list or role to delete (use RoleRepresentation)
  1022. :return: Keycloak server response
  1023. """
  1024. payload = roles if isinstance(roles, list) else [roles]
  1025. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  1026. data_raw = self.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  1027. data=json.dumps(payload))
  1028. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1029. def get_authentication_flows(self):
  1030. """
  1031. Get authentication flows. Returns all flow details
  1032. AuthenticationFlowRepresentation
  1033. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1034. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1035. """
  1036. params_path = {"realm-name": self.realm_name}
  1037. data_raw = self.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  1038. return raise_error_from_response(data_raw, KeycloakGetError)
  1039. def get_authentication_flow_for_id(self, flow_id):
  1040. """
  1041. Get one authentication flow by it's id/alias. Returns all flow details
  1042. AuthenticationFlowRepresentation
  1043. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1044. :param flow_id: the id of a flow NOT it's alias
  1045. :return: Keycloak server response (AuthenticationFlowRepresentation)
  1046. """
  1047. params_path = {"realm-name": self.realm_name, "flow-id": flow_id}
  1048. data_raw = self.raw_get(URL_ADMIN_FLOWS_ALIAS.format(**params_path))
  1049. return raise_error_from_response(data_raw, KeycloakGetError)
  1050. def create_authentication_flow(self, payload, skip_exists=False):
  1051. """
  1052. Create a new authentication flow
  1053. AuthenticationFlowRepresentation
  1054. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1055. :param payload: AuthenticationFlowRepresentation
  1056. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1057. :return: Keycloak server response (RoleRepresentation)
  1058. """
  1059. params_path = {"realm-name": self.realm_name}
  1060. data_raw = self.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  1061. data=payload)
  1062. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1063. def copy_authentication_flow(self, payload, flow_alias):
  1064. """
  1065. Copy existing authentication flow under a new name. The new name is given as 'newName' attribute of the passed payload.
  1066. :param payload: JSON containing 'newName' attribute
  1067. :param flow_alias: the flow alias
  1068. :return: Keycloak server response (RoleRepresentation)
  1069. """
  1070. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1071. data_raw = self.raw_post(URL_ADMIN_FLOWS_COPY.format(**params_path),
  1072. data=payload)
  1073. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1074. def get_authentication_flow_executions(self, flow_alias):
  1075. """
  1076. Get authentication flow executions. Returns all execution steps
  1077. :param flow_alias: the flow alias
  1078. :return: Response(json)
  1079. """
  1080. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1081. data_raw = self.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  1082. return raise_error_from_response(data_raw, KeycloakGetError)
  1083. def update_authentication_flow_executions(self, payload, flow_alias):
  1084. """
  1085. Update an authentication flow execution
  1086. AuthenticationExecutionInfoRepresentation
  1087. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1088. :param payload: AuthenticationExecutionInfoRepresentation
  1089. :param flow_alias: The flow alias
  1090. :return: Keycloak server response
  1091. """
  1092. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1093. data_raw = self.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  1094. data=payload)
  1095. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1096. def create_authentication_flow_execution(self, payload, flow_alias):
  1097. """
  1098. Create an authentication flow execution
  1099. AuthenticationExecutionInfoRepresentation
  1100. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationexecutioninforepresentation
  1101. :param payload: AuthenticationExecutionInfoRepresentation
  1102. :param flow_alias: The flow alias
  1103. :return: Keycloak server response
  1104. """
  1105. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1106. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_EXEUCUTION.format(**params_path),
  1107. data=payload)
  1108. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1109. def create_authentication_flow_subflow(self, payload, flow_alias, skip_exists=False):
  1110. """
  1111. Create a new sub authentication flow for a given authentication flow
  1112. AuthenticationFlowRepresentation
  1113. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authenticationflowrepresentation
  1114. :param payload: AuthenticationFlowRepresentation
  1115. :param flow_alias: The flow alias
  1116. :param skip_exists: If true then do not raise an error if authentication flow already exists
  1117. :return: Keycloak server response (RoleRepresentation)
  1118. """
  1119. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  1120. data_raw = self.raw_post(URL_ADMIN_FLOWS_EXECUTIONS_FLOW.format(**params_path),
  1121. data=payload)
  1122. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
  1123. def sync_users(self, storage_id, action):
  1124. """
  1125. Function to trigger user sync from provider
  1126. :param storage_id: The id of the user storage provider
  1127. :param action: Action can be "triggerFullSync" or "triggerChangedUsersSync"
  1128. :return:
  1129. """
  1130. data = {'action': action}
  1131. params_query = {"action": action}
  1132. params_path = {"realm-name": self.realm_name, "id": storage_id}
  1133. data_raw = self.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  1134. data=json.dumps(data), **params_query)
  1135. return raise_error_from_response(data_raw, KeycloakGetError)
  1136. def get_client_scopes(self):
  1137. """
  1138. Get representation of the client scopes for the realm where we are connected to
  1139. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1140. :return: Keycloak server response Array of (ClientScopeRepresentation)
  1141. """
  1142. params_path = {"realm-name": self.realm_name}
  1143. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPES.format(**params_path))
  1144. return raise_error_from_response(data_raw, KeycloakGetError)
  1145. def get_client_scope(self, client_scope_id):
  1146. """
  1147. Get representation of the client scopes for the realm where we are connected to
  1148. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientscopes
  1149. :param client_scope_id: The id of the client scope
  1150. :return: Keycloak server response (ClientScopeRepresentation)
  1151. """
  1152. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1153. data_raw = self.raw_get(URL_ADMIN_CLIENT_SCOPE.format(**params_path))
  1154. return raise_error_from_response(data_raw, KeycloakGetError)
  1155. def add_mapper_to_client_scope(self, client_scope_id, payload):
  1156. """
  1157. Add a mapper to a client scope
  1158. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1159. :param client_scope_id: The id of the client scope
  1160. :param payload: ProtocolMapperRepresentation
  1161. :return: Keycloak server Response
  1162. """
  1163. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id}
  1164. data_raw = self.raw_post(
  1165. URL_ADMIN_CLIENT_SCOPES_ADD_MAPPER.format(**params_path), data=json.dumps(payload))
  1166. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1167. def delete_mapper_from_client_scope(self, client_scope_id, protocol_mppaer_id):
  1168. """
  1169. Delete a mapper from a client scope
  1170. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_delete_mapper
  1171. :param client_scope_id: The id of the client scope
  1172. :param payload: ProtocolMapperRepresentation
  1173. :return: Keycloak server Response
  1174. """
  1175. params_path = {"realm-name": self.realm_name, "scope-id": client_scope_id,
  1176. "protocol-mapper-id": protocol_mppaer_id}
  1177. data_raw = self.raw_delete(
  1178. URL_ADMIN_CLIENT_SCOPES_MAPPERS.format(**params_path))
  1179. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1180. def add_mapper_to_client(self, client_id, payload):
  1181. """
  1182. Add a mapper to a client
  1183. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_create_mapper
  1184. :param client_id: The id of the client
  1185. :param payload: ProtocolMapperRepresentation
  1186. :return: Keycloak server Response
  1187. """
  1188. params_path = {"realm-name": self.realm_name, "id": client_id}
  1189. data_raw = self.raw_post(
  1190. URL_ADMIN_CLIENT_PROTOCOL_MAPPER.format(**params_path), data=json.dumps(payload))
  1191. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1192. def generate_client_secrets(self, client_id):
  1193. """
  1194. Generate a new secret for the client
  1195. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_regeneratesecret
  1196. :param client_id: id of client (not client-id)
  1197. :return: Keycloak server response (ClientRepresentation)
  1198. """
  1199. params_path = {"realm-name": self.realm_name, "id": client_id}
  1200. data_raw = self.raw_post(URL_ADMIN_CLIENT_SECRETS.format(**params_path), data=None)
  1201. return raise_error_from_response(data_raw, KeycloakGetError)
  1202. def get_client_secrets(self, client_id):
  1203. """
  1204. Get representation of the client secrets
  1205. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_getclientsecret
  1206. :param client_id: id of client (not client-id)
  1207. :return: Keycloak server response (ClientRepresentation)
  1208. """
  1209. params_path = {"realm-name": self.realm_name, "id": client_id}
  1210. data_raw = self.raw_get(URL_ADMIN_CLIENT_SECRETS.format(**params_path))
  1211. return raise_error_from_response(data_raw, KeycloakGetError)
  1212. def get_components(self, query=None):
  1213. """
  1214. Return a list of components, filtered according to query parameters
  1215. ComponentRepresentation
  1216. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1217. :param query: Query parameters (optional)
  1218. :return: components list
  1219. """
  1220. params_path = {"realm-name": self.realm_name}
  1221. data_raw = self.raw_get(URL_ADMIN_COMPONENTS.format(**params_path),
  1222. data=None, **query)
  1223. return raise_error_from_response(data_raw, KeycloakGetError)
  1224. def create_component(self, payload):
  1225. """
  1226. Create a new component.
  1227. ComponentRepresentation
  1228. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1229. :param payload: ComponentRepresentation
  1230. :return: UserRepresentation
  1231. """
  1232. params_path = {"realm-name": self.realm_name}
  1233. data_raw = self.raw_post(URL_ADMIN_COMPONENTS.format(**params_path),
  1234. data=json.dumps(payload))
  1235. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201])
  1236. def get_component(self, component_id):
  1237. """
  1238. Get representation of the component
  1239. :param component_id: Component id
  1240. ComponentRepresentation
  1241. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1242. :return: ComponentRepresentation
  1243. """
  1244. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1245. data_raw = self.raw_get(URL_ADMIN_COMPONENT.format(**params_path))
  1246. return raise_error_from_response(data_raw, KeycloakGetError)
  1247. def update_component(self, component_id, payload):
  1248. """
  1249. Update the component
  1250. :param component_id: Component id
  1251. :param payload: ComponentRepresentation
  1252. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_componentrepresentation
  1253. :return: Http response
  1254. """
  1255. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1256. data_raw = self.raw_put(URL_ADMIN_COMPONENT.format(**params_path),
  1257. data=json.dumps(payload))
  1258. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1259. def delete_component(self, component_id):
  1260. """
  1261. Delete the component
  1262. :param component_id: Component id
  1263. :return: Http response
  1264. """
  1265. params_path = {"realm-name": self.realm_name, "component-id": component_id}
  1266. data_raw = self.raw_delete(URL_ADMIN_COMPONENT.format(**params_path))
  1267. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  1268. def get_keys(self):
  1269. """
  1270. Return a list of keys, filtered according to query parameters
  1271. KeysMetadataRepresentation
  1272. https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_key_resource
  1273. :return: keys list
  1274. """
  1275. params_path = {"realm-name": self.realm_name}
  1276. data_raw = self.raw_get(URL_ADMIN_KEYS.format(**params_path),
  1277. data=None)
  1278. return raise_error_from_response(data_raw, KeycloakGetError)
  1279. def raw_get(self, *args, **kwargs):
  1280. """
  1281. Calls connection.raw_get.
  1282. If auto_refresh is set for *get* and *access_token* is expired, it will refresh the token
  1283. and try *get* once more.
  1284. """
  1285. r = self.connection.raw_get(*args, **kwargs)
  1286. if 'get' in self.auto_refresh_token and r.status_code == 401:
  1287. self.refresh_token()
  1288. return self.connection.raw_get(*args, **kwargs)
  1289. return r
  1290. def raw_post(self, *args, **kwargs):
  1291. """
  1292. Calls connection.raw_post.
  1293. If auto_refresh is set for *post* and *access_token* is expired, it will refresh the token
  1294. and try *post* once more.
  1295. """
  1296. r = self.connection.raw_post(*args, **kwargs)
  1297. if 'post' in self.auto_refresh_token and r.status_code == 401:
  1298. self.refresh_token()
  1299. return self.connection.raw_post(*args, **kwargs)
  1300. return r
  1301. def raw_put(self, *args, **kwargs):
  1302. """
  1303. Calls connection.raw_put.
  1304. If auto_refresh is set for *put* and *access_token* is expired, it will refresh the token
  1305. and try *put* once more.
  1306. """
  1307. r = self.connection.raw_put(*args, **kwargs)
  1308. if 'put' in self.auto_refresh_token and r.status_code == 401:
  1309. self.refresh_token()
  1310. return self.connection.raw_put(*args, **kwargs)
  1311. return r
  1312. def raw_delete(self, *args, **kwargs):
  1313. """
  1314. Calls connection.raw_delete.
  1315. If auto_refresh is set for *delete* and *access_token* is expired, it will refresh the token
  1316. and try *delete* once more.
  1317. """
  1318. r = self.connection.raw_delete(*args, **kwargs)
  1319. if 'delete' in self.auto_refresh_token and r.status_code == 401:
  1320. self.refresh_token()
  1321. return self.connection.raw_delete(*args, **kwargs)
  1322. return r
  1323. def get_token(self):
  1324. self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id,
  1325. realm_name=self.user_realm_name or self.realm_name, verify=self.verify,
  1326. client_secret_key=self.client_secret_key,
  1327. custom_headers=self.custom_headers)
  1328. grant_type = ["password"]
  1329. if self.client_secret_key:
  1330. grant_type = ["client_credentials"]
  1331. self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type)
  1332. headers = {
  1333. 'Authorization': 'Bearer ' + self.token.get('access_token'),
  1334. 'Content-Type': 'application/json'
  1335. }
  1336. if self.custom_headers is not None:
  1337. # merge custom headers to main headers
  1338. headers.update(self.custom_headers)
  1339. self._connection = ConnectionManager(base_url=self.server_url,
  1340. headers=headers,
  1341. timeout=60,
  1342. verify=self.verify)
  1343. def refresh_token(self):
  1344. refresh_token = self.token.get('refresh_token')
  1345. try:
  1346. self.token = self.keycloak_openid.refresh_token(refresh_token)
  1347. except KeycloakGetError as e:
  1348. if e.response_code == 400 and (b'Refresh token expired' in e.response_body or
  1349. b'Token is not active' in e.response_body):
  1350. self.get_token()
  1351. else:
  1352. raise
  1353. self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token'))