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.

387 lines
14 KiB

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
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
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
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
3 years ago
6 years ago
6 years ago
6 years ago
7 years ago
  1. [![CircleCI](https://github.com/marcospereirampj/python-keycloak/actions/workflows/daily.yaml/badge.svg)](https://github.com/marcospereirampj/python-keycloak/)
  2. [![Documentation Status](https://readthedocs.org/projects/python-keycloak/badge/?version=latest)](http://python-keycloak.readthedocs.io/en/latest/?badge=latest)
  3. # Python Keycloak
  4. For review- see https://github.com/marcospereirampj/python-keycloak
  5. **python-keycloak** is a Python package providing access to the Keycloak API.
  6. ## Installation
  7. ### Via Pypi Package:
  8. `$ pip install python-keycloak`
  9. ### Manually
  10. `$ python setup.py install`
  11. ## Dependencies
  12. python-keycloak depends on:
  13. - Python 3
  14. - [requests](https://requests.readthedocs.io)
  15. - [python-jose](http://python-jose.readthedocs.io/en/latest/)
  16. - [urllib3](https://urllib3.readthedocs.io/en/stable/)
  17. ### Tests Dependencies
  18. - [tox](https://tox.readthedocs.io/)
  19. - [pytest](https://docs.pytest.org/en/latest/)
  20. - [pytest-cov](https://github.com/pytest-dev/pytest-cov)
  21. - [wheel](https://github.com/pypa/wheel)
  22. ## Bug reports
  23. Please report bugs and feature requests at
  24. https://github.com/marcospereirampj/python-keycloak/issues
  25. ## Documentation
  26. The documentation for python-keycloak is available on [readthedocs](http://python-keycloak.readthedocs.io).
  27. ## Usage
  28. ```python
  29. from keycloak import KeycloakOpenID
  30. # Configure client
  31. keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
  32. client_id="example_client",
  33. realm_name="example_realm",
  34. client_secret_key="secret")
  35. # Get WellKnown
  36. config_well_known = keycloak_openid.well_known()
  37. # Get Code With Oauth Authorization Request
  38. auth_url = keycloak_openid.auth_url(
  39. redirect_uri="your_call_back_url",
  40. scope="email",
  41. state="your_state_info")
  42. # Get Access Token With Code
  43. access_token = keycloak_openid.token(
  44. grant_type='authorization_code',
  45. code='the_code_you_get_from_auth_url_callback',
  46. redirect_uri="your_call_back_url")
  47. # Get Token
  48. token = keycloak_openid.token("user", "password")
  49. token = keycloak_openid.token("user", "password", totp="012345")
  50. # Get token using Token Exchange
  51. token = keycloak_openid.exchange_token(token['access_token'], "my_client", "other_client", "some_user")
  52. # Get Userinfo
  53. userinfo = keycloak_openid.userinfo(token['access_token'])
  54. # Refresh token
  55. token = keycloak_openid.refresh_token(token['refresh_token'])
  56. # Logout
  57. keycloak_openid.logout(token['refresh_token'])
  58. # Get Certs
  59. certs = keycloak_openid.certs()
  60. # Get RPT (Entitlement)
  61. token = keycloak_openid.token("user", "password")
  62. rpt = keycloak_openid.entitlement(token['access_token'], "resource_id")
  63. # Introspect RPT
  64. token_rpt_info = keycloak_openid.introspect(keycloak_openid.introspect(token['access_token'], rpt=rpt['rpt'],
  65. token_type_hint="requesting_party_token"))
  66. # Introspect Token
  67. token_info = keycloak_openid.introspect(token['access_token'])
  68. # Decode Token
  69. KEYCLOAK_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + keycloak_openid.public_key() + "\n-----END PUBLIC KEY-----"
  70. options = {"verify_signature": True, "verify_aud": True, "verify_exp": True}
  71. token_info = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)
  72. # Get permissions by token
  73. token = keycloak_openid.token("user", "password")
  74. keycloak_openid.load_authorization_config("example-authz-config.json")
  75. policies = keycloak_openid.get_policies(token['access_token'], method_token_info='decode', key=KEYCLOAK_PUBLIC_KEY)
  76. permissions = keycloak_openid.get_permissions(token['access_token'], method_token_info='introspect')
  77. # Get UMA-permissions by token
  78. token = keycloak_openid.token("user", "password")
  79. permissions = keycloak_openid.uma_permissions(token['access_token'])
  80. # Get UMA-permissions by token with specific resource and scope requested
  81. token = keycloak_openid.token("user", "password")
  82. permissions = keycloak_openid.uma_permissions(token['access_token'], permissions="Resource#Scope")
  83. # Get auth status for a specific resource and scope by token
  84. token = keycloak_openid.token("user", "password")
  85. auth_status = keycloak_openid.has_uma_access(token['access_token'], "Resource#Scope")
  86. # KEYCLOAK ADMIN
  87. from keycloak import KeycloakAdmin
  88. from keycloak import KeycloakOpenIDConnection
  89. keycloak_connection = KeycloakOpenIDConnection(
  90. server_url="http://localhost:8080/",
  91. username='example-admin',
  92. password='secret',
  93. realm_name="master",
  94. user_realm_name="only_if_other_realm_than_master",
  95. client_id="my_client",
  96. client_secret_key="client-secret",
  97. verify=True)
  98. keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
  99. # Add user
  100. new_user = keycloak_admin.create_user({"email": "example@example.com",
  101. "username": "example@example.com",
  102. "enabled": True,
  103. "firstName": "Example",
  104. "lastName": "Example"})
  105. # Add user and raise exception if username already exists
  106. # exist_ok currently defaults to True for backwards compatibility reasons
  107. new_user = keycloak_admin.create_user({"email": "example@example.com",
  108. "username": "example@example.com",
  109. "enabled": True,
  110. "firstName": "Example",
  111. "lastName": "Example"},
  112. exist_ok=False)
  113. # Add user and set password
  114. new_user = keycloak_admin.create_user({"email": "example@example.com",
  115. "username": "example@example.com",
  116. "enabled": True,
  117. "firstName": "Example",
  118. "lastName": "Example",
  119. "credentials": [{"value": "secret","type": "password",}]})
  120. # Add user and specify a locale
  121. new_user = keycloak_admin.create_user({"email": "example@example.fr",
  122. "username": "example@example.fr",
  123. "enabled": True,
  124. "firstName": "Example",
  125. "lastName": "Example",
  126. "attributes": {
  127. "locale": ["fr"]
  128. }})
  129. # User counter
  130. count_users = keycloak_admin.users_count()
  131. # Get users Returns a list of users, filtered according to query parameters
  132. users = keycloak_admin.get_users({})
  133. # Get user ID from username
  134. user_id_keycloak = keycloak_admin.get_user_id("username-keycloak")
  135. # Get User
  136. user = keycloak_admin.get_user("user-id-keycloak")
  137. # Update User
  138. response = keycloak_admin.update_user(user_id="user-id-keycloak",
  139. payload={'firstName': 'Example Update'})
  140. # Update User Password
  141. response = keycloak_admin.set_user_password(user_id="user-id-keycloak", password="secret", temporary=True)
  142. # Get User Credentials
  143. credentials = keycloak_admin.get_credentials(user_id='user_id')
  144. # Get User Credential by ID
  145. credential = keycloak_admin.get_credential(user_id='user_id', credential_id='credential_id')
  146. # Delete User Credential
  147. response = keycloak_admin.delete_credential(user_id='user_id', credential_id='credential_id')
  148. # Delete User
  149. response = keycloak_admin.delete_user(user_id="user-id-keycloak")
  150. # Get consents granted by the user
  151. consents = keycloak_admin.consents_user(user_id="user-id-keycloak")
  152. # Send User Action
  153. response = keycloak_admin.send_update_account(user_id="user-id-keycloak",
  154. payload=['UPDATE_PASSWORD'])
  155. # Send Verify Email
  156. response = keycloak_admin.send_verify_email(user_id="user-id-keycloak")
  157. # Get sessions associated with the user
  158. sessions = keycloak_admin.get_sessions(user_id="user-id-keycloak")
  159. # Get themes, social providers, auth providers, and event listeners available on this server
  160. server_info = keycloak_admin.get_server_info()
  161. # Get clients belonging to the realm Returns a list of clients belonging to the realm
  162. clients = keycloak_admin.get_clients()
  163. # Get client - id (not client-id) from client by name
  164. client_id = keycloak_admin.get_client_id("my-client")
  165. # Get representation of the client - id of client (not client-id)
  166. client = keycloak_admin.get_client(client_id="client_id")
  167. # Get all roles for the realm or client
  168. realm_roles = keycloak_admin.get_realm_roles()
  169. # Get all roles for the realm or client that their names includes the searched text
  170. realm_roles = keycloak_admin.get_realm_roles(search_text="CompanyA_")
  171. # Get all roles for the client
  172. client_roles = keycloak_admin.get_client_roles(client_id="client_id")
  173. # Get client role
  174. role = keycloak_admin.get_client_role(client_id="client_id", role_name="role_name")
  175. # Warning: Deprecated
  176. # Get client role id from name
  177. role_id = keycloak_admin.get_client_role_id(client_id="client_id", role_name="test")
  178. # Create client role
  179. keycloak_admin.create_client_role(client_role_id='client_id', payload={'name': 'roleName', 'clientRole': True})
  180. # Assign client role to user. Note that BOTH role_name and role_id appear to be required.
  181. keycloak_admin.assign_client_role(client_id="client_id", user_id="user_id", role_id="role_id", role_name="test")
  182. # Retrieve client roles of a user.
  183. keycloak_admin.get_client_roles_of_user(user_id="user_id", client_id="client_id")
  184. # Retrieve available client roles of a user.
  185. keycloak_admin.get_available_client_roles_of_user(user_id="user_id", client_id="client_id")
  186. # Retrieve composite client roles of a user.
  187. keycloak_admin.get_composite_client_roles_of_user(user_id="user_id", client_id="client_id")
  188. # Delete client roles of a user.
  189. keycloak_admin.delete_client_roles_of_user(client_id="client_id", user_id="user_id", roles={"id": "role-id"})
  190. keycloak_admin.delete_client_roles_of_user(client_id="client_id", user_id="user_id", roles=[{"id": "role-id_1"}, {"id": "role-id_2"}])
  191. # Get the client authorization settings
  192. client_authz_settings = get_client_authz_settings(client_id="client_id")
  193. # Get all client authorization resources
  194. client_resources = get_client_authz_resources(client_id="client_id")
  195. # Get all client authorization scopes
  196. client_scopes = get_client_authz_scopes(client_id="client_id")
  197. # Get all client authorization permissions
  198. client_permissions = get_client_authz_permissions(client_id="client_id")
  199. # Get all client authorization policies
  200. client_policies = get_client_authz_policies(client_id="client_id")
  201. # Create new group
  202. group = keycloak_admin.create_group({"name": "Example Group"})
  203. # Get all groups
  204. groups = keycloak_admin.get_groups()
  205. # Get group
  206. group = keycloak_admin.get_group(group_id='group_id')
  207. # Get group by name
  208. group = keycloak_admin.get_group_by_path(path='/group/subgroup')
  209. # Function to trigger user sync from provider
  210. sync_users(storage_id="storage_di", action="action")
  211. # Get client role id from name
  212. role_id = keycloak_admin.get_client_role_id(client_id=client_id, role_name="test")
  213. # Assign client role to user. Note that BOTH role_name and role_id appear to be required.
  214. keycloak_admin.assign_client_role(client_id=client_id, user_id=user_id, role_id=role_id, role_name="test")
  215. # Assign realm roles to user
  216. keycloak_admin.assign_realm_roles(user_id=user_id, roles=realm_roles)
  217. # Assign realm roles to client's scope
  218. keycloak_admin.assign_realm_roles_to_client_scope(client_id=client_id, roles=realm_roles)
  219. # Get realm roles assigned to client's scope
  220. keycloak_admin.get_realm_roles_of_client_scope(client_id=client_id)
  221. # Remove realm roles assigned to client's scope
  222. keycloak_admin.delete_realm_roles_of_client_scope(client_id=client_id, roles=realm_roles)
  223. another_client_id = keycloak_admin.get_client_id("my-client-2")
  224. # Assign client roles to client's scope
  225. keycloak_admin.assign_client_roles_to_client_scope(client_id=another_client_id, client_roles_owner_id=client_id, roles=client_roles)
  226. # Get client roles assigned to client's scope
  227. keycloak_admin.get_client_roles_of_client_scope(client_id=another_client_id, client_roles_owner_id=client_id)
  228. # Remove client roles assigned to client's scope
  229. keycloak_admin.delete_client_roles_of_client_scope(client_id=another_client_id, client_roles_owner_id=client_id, roles=client_roles)
  230. # Get all IDP Providers
  231. idps = keycloak_admin.get_idps()
  232. # Get a specific IDP Provider, using its alias
  233. idp = keycloak_admin.get_idp("idp-alias")
  234. # Create a new Realm
  235. keycloak_admin.create_realm(payload={"realm": "demo"}, skip_exists=False)
  236. # Changing Realm
  237. keycloak_admin = KeycloakAdmin(realm_name="main", ...)
  238. keycloak_admin.get_users() # Get user in main realm
  239. keycloak_admin.change_current_realm("demo") # Change realm to 'demo'
  240. keycloak_admin.get_current_realm() # Gives 'demo'
  241. keycloak_admin.get_users() # Get users in realm 'demo'
  242. keycloak_admin.create_user(...) # Creates a new user in 'demo'
  243. # Get User events
  244. keycloak_admin.get_events(query={'type': 'LOGIN',
  245. 'user': user['id'],
  246. 'dateFrom': '2023-08-02'})
  247. # Get Admin events
  248. keycloak_admin.get_admin_events(query={'resourceTypes': 'USER',
  249. 'operationTypes': 'UPDATE',
  250. 'resourcePath': 'users/' + user['id'],
  251. 'dateFrom': '2023-08-02'
  252. })
  253. # KEYCLOAK UMA
  254. from keycloak import KeycloakOpenIDConnection
  255. from keycloak import KeycloakUMA
  256. keycloak_connection = KeycloakOpenIDConnection(
  257. server_url="http://localhost:8080/",
  258. realm_name="master",
  259. client_id="my_client",
  260. client_secret_key="client-secret")
  261. keycloak_uma = KeycloakUMA(connection=keycloak_connection)
  262. # Create a resource set
  263. resource_set = keycloak_uma.resource_set_create({
  264. "name": "example_resource",
  265. "scopes": ["example:read", "example:write"],
  266. "type": "urn:example"})
  267. # List resource sets
  268. resource_sets = uma.resource_set_list()
  269. # get resource set
  270. latest_resource = uma.resource_set_read(resource_set["_id"])
  271. # update resource set
  272. latest_resource["name"] = "New Resource Name"
  273. uma.resource_set_update(resource_set["_id"], latest_resource)
  274. # delete resource set
  275. uma.resource_set_delete(resource_id=resource_set["_id"])
  276. ```