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.

384 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
3 years ago
6 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. ## Contributors
  28. - [Agriness Team](http://www.agriness.com/pt/)
  29. - [Marcos Pereira](marcospereira.mpj@gmail.com)
  30. - [Martin Devlin](https://bitbucket.org/devlinmpearson/)
  31. - [Shon T. Urbas](https://bitbucket.org/surbas/)
  32. - [Markus Spanier](https://bitbucket.org/spanierm/)
  33. - [Remco Kranenburg](https://bitbucket.org/Remco47/)
  34. - [Armin](https://bitbucket.org/arminfelder/)
  35. - [njordr](https://bitbucket.org/njordr/)
  36. - [Josha Inglis](https://bitbucket.org/joshainglis/)
  37. - [Alex](https://bitbucket.org/alex_zel/)
  38. - [Ewan Jone](https://bitbucket.org/kisamoto/)
  39. - [Lukas Martini](https://github.com/lutoma)
  40. - [Adamatics](https://www.adamatics.com)
  41. ## Usage
  42. ```python
  43. from keycloak import KeycloakOpenID
  44. # Configure client
  45. keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
  46. client_id="example_client",
  47. realm_name="example_realm",
  48. client_secret_key="secret")
  49. # Get WellKnown
  50. config_well_known = keycloak_openid.well_known()
  51. # Get Code With Oauth Authorization Request
  52. auth_url = keycloak_openid.auth_url(
  53. redirect_uri="your_call_back_url",
  54. scope="email",
  55. state="your_state_info")
  56. # Get Access Token With Code
  57. access_token = keycloak_openid.token(
  58. grant_type='authorization_code',
  59. code='the_code_you_get_from_auth_url_callback',
  60. redirect_uri="your_call_back_url")
  61. # Get Token
  62. token = keycloak_openid.token("user", "password")
  63. token = keycloak_openid.token("user", "password", totp="012345")
  64. # Get token using Token Exchange
  65. token = keycloak_openid.exchange_token(token['access_token'], "my_client", "other_client", "some_user")
  66. # Get Userinfo
  67. userinfo = keycloak_openid.userinfo(token['access_token'])
  68. # Refresh token
  69. token = keycloak_openid.refresh_token(token['refresh_token'])
  70. # Logout
  71. keycloak_openid.logout(token['refresh_token'])
  72. # Get Certs
  73. certs = keycloak_openid.certs()
  74. # Get RPT (Entitlement)
  75. token = keycloak_openid.token("user", "password")
  76. rpt = keycloak_openid.entitlement(token['access_token'], "resource_id")
  77. # Instropect RPT
  78. token_rpt_info = keycloak_openid.introspect(keycloak_openid.introspect(token['access_token'], rpt=rpt['rpt'],
  79. token_type_hint="requesting_party_token"))
  80. # Introspect Token
  81. token_info = keycloak_openid.introspect(token['access_token'])
  82. # Decode Token
  83. KEYCLOAK_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + keycloak_openid.public_key() + "\n-----END PUBLIC KEY-----"
  84. options = {"verify_signature": True, "verify_aud": True, "verify_exp": True}
  85. token_info = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)
  86. # Get permissions by token
  87. token = keycloak_openid.token("user", "password")
  88. keycloak_openid.load_authorization_config("example-authz-config.json")
  89. policies = keycloak_openid.get_policies(token['access_token'], method_token_info='decode', key=KEYCLOAK_PUBLIC_KEY)
  90. permissions = keycloak_openid.get_permissions(token['access_token'], method_token_info='introspect')
  91. # Get UMA-permissions by token
  92. token = keycloak_openid.token("user", "password")
  93. permissions = keycloak_openid.uma_permissions(token['access_token'])
  94. # Get UMA-permissions by token with specific resource and scope requested
  95. token = keycloak_openid.token("user", "password")
  96. permissions = keycloak_openid.uma_permissions(token['access_token'], permissions="Resource#Scope")
  97. # Get auth status for a specific resource and scope by token
  98. token = keycloak_openid.token("user", "password")
  99. auth_status = keycloak_openid.has_uma_access(token['access_token'], "Resource#Scope")
  100. # KEYCLOAK ADMIN
  101. from keycloak import KeycloakAdmin
  102. from keycloak import KeycloakOpenIDConnection
  103. keycloak_connection = KeycloakOpenIDConnection(
  104. server_url="http://localhost:8080/",
  105. username='example-admin',
  106. password='secret',
  107. realm_name="master",
  108. user_realm_name="only_if_other_realm_than_master",
  109. client_id="my_client",
  110. client_secret_key="client-secret",
  111. verify=True)
  112. keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
  113. # Add user
  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. # Add user and raise exception if username already exists
  120. # exist_ok currently defaults to True for backwards compatibility reasons
  121. new_user = keycloak_admin.create_user({"email": "example@example.com",
  122. "username": "example@example.com",
  123. "enabled": True,
  124. "firstName": "Example",
  125. "lastName": "Example"},
  126. exist_ok=False)
  127. # Add user and set password
  128. new_user = keycloak_admin.create_user({"email": "example@example.com",
  129. "username": "example@example.com",
  130. "enabled": True,
  131. "firstName": "Example",
  132. "lastName": "Example",
  133. "credentials": [{"value": "secret","type": "password",}]})
  134. # Add user and specify a locale
  135. new_user = keycloak_admin.create_user({"email": "example@example.fr",
  136. "username": "example@example.fr",
  137. "enabled": True,
  138. "firstName": "Example",
  139. "lastName": "Example",
  140. "attributes": {
  141. "locale": ["fr"]
  142. }})
  143. # User counter
  144. count_users = keycloak_admin.users_count()
  145. # Get users Returns a list of users, filtered according to query parameters
  146. users = keycloak_admin.get_users({})
  147. # Get user ID from username
  148. user_id_keycloak = keycloak_admin.get_user_id("username-keycloak")
  149. # Get User
  150. user = keycloak_admin.get_user("user-id-keycloak")
  151. # Update User
  152. response = keycloak_admin.update_user(user_id="user-id-keycloak",
  153. payload={'firstName': 'Example Update'})
  154. # Update User Password
  155. response = keycloak_admin.set_user_password(user_id="user-id-keycloak", password="secret", temporary=True)
  156. # Get User Credentials
  157. credentials = keycloak_admin.get_credentials(user_id='user_id')
  158. # Get User Credential by ID
  159. credential = keycloak_admin.get_credential(user_id='user_id', credential_id='credential_id')
  160. # Delete User Credential
  161. response = keycloak_admin.delete_credential(user_id='user_id', credential_id='credential_id')
  162. # Delete User
  163. response = keycloak_admin.delete_user(user_id="user-id-keycloak")
  164. # Get consents granted by the user
  165. consents = keycloak_admin.consents_user(user_id="user-id-keycloak")
  166. # Send User Action
  167. response = keycloak_admin.send_update_account(user_id="user-id-keycloak",
  168. payload=['UPDATE_PASSWORD'])
  169. # Send Verify Email
  170. response = keycloak_admin.send_verify_email(user_id="user-id-keycloak")
  171. # Get sessions associated with the user
  172. sessions = keycloak_admin.get_sessions(user_id="user-id-keycloak")
  173. # Get themes, social providers, auth providers, and event listeners available on this server
  174. server_info = keycloak_admin.get_server_info()
  175. # Get clients belonging to the realm Returns a list of clients belonging to the realm
  176. clients = keycloak_admin.get_clients()
  177. # Get client - id (not client-id) from client by name
  178. client_id = keycloak_admin.get_client_id("my-client")
  179. # Get representation of the client - id of client (not client-id)
  180. client = keycloak_admin.get_client(client_id="client_id")
  181. # Get all roles for the realm or client
  182. realm_roles = keycloak_admin.get_realm_roles()
  183. # Get all roles for the client
  184. client_roles = keycloak_admin.get_client_roles(client_id="client_id")
  185. # Get client role
  186. role = keycloak_admin.get_client_role(client_id="client_id", role_name="role_name")
  187. # Warning: Deprecated
  188. # Get client role id from name
  189. role_id = keycloak_admin.get_client_role_id(client_id="client_id", role_name="test")
  190. # Create client role
  191. keycloak_admin.create_client_role(client_role_id='client_id', payload={'name': 'roleName', 'clientRole': True})
  192. # Assign client role to user. Note that BOTH role_name and role_id appear to be required.
  193. keycloak_admin.assign_client_role(client_id="client_id", user_id="user_id", role_id="role_id", role_name="test")
  194. # Retrieve client roles of a user.
  195. keycloak_admin.get_client_roles_of_user(user_id="user_id", client_id="client_id")
  196. # Retrieve available client roles of a user.
  197. keycloak_admin.get_available_client_roles_of_user(user_id="user_id", client_id="client_id")
  198. # Retrieve composite client roles of a user.
  199. keycloak_admin.get_composite_client_roles_of_user(user_id="user_id", client_id="client_id")
  200. # Delete client roles of a user.
  201. keycloak_admin.delete_client_roles_of_user(client_id="client_id", user_id="user_id", roles={"id": "role-id"})
  202. keycloak_admin.delete_client_roles_of_user(client_id="client_id", user_id="user_id", roles=[{"id": "role-id_1"}, {"id": "role-id_2"}])
  203. # Get the client authorization settings
  204. client_authz_settings = get_client_authz_settings(client_id="client_id")
  205. # Get all client authorization resources
  206. client_resources = get_client_authz_resources(client_id="client_id")
  207. # Get all client authorization scopes
  208. client_scopes = get_client_authz_scopes(client_id="client_id")
  209. # Get all client authorization permissions
  210. client_permissions = get_client_authz_permissions(client_id="client_id")
  211. # Get all client authorization policies
  212. client_policies = get_client_authz_policies(client_id="client_id")
  213. # Create new group
  214. group = keycloak_admin.create_group({"name": "Example Group"})
  215. # Get all groups
  216. groups = keycloak_admin.get_groups()
  217. # Get group
  218. group = keycloak_admin.get_group(group_id='group_id')
  219. # Get group by name
  220. group = keycloak_admin.get_group_by_path(path='/group/subgroup', search_in_subgroups=True)
  221. # Function to trigger user sync from provider
  222. sync_users(storage_id="storage_di", action="action")
  223. # Get client role id from name
  224. role_id = keycloak_admin.get_client_role_id(client_id=client_id, role_name="test")
  225. # Assign client role to user. Note that BOTH role_name and role_id appear to be required.
  226. keycloak_admin.assign_client_role(client_id=client_id, user_id=user_id, role_id=role_id, role_name="test")
  227. # Assign realm roles to user
  228. keycloak_admin.assign_realm_roles(user_id=user_id, roles=realm_roles)
  229. # Assign realm roles to client's scope
  230. keycloak_admin.assign_realm_roles_to_client_scope(client_id=client_id, roles=realm_roles)
  231. # Get realm roles assigned to client's scope
  232. keycloak_admin.get_realm_roles_of_client_scope(client_id=client_id)
  233. # Remove realm roles assigned to client's scope
  234. keycloak_admin.delete_realm_roles_of_client_scope(client_id=client_id, roles=realm_roles)
  235. another_client_id = keycloak_admin.get_client_id("my-client-2")
  236. # Assign client roles to client's scope
  237. keycloak_admin.assign_client_roles_to_client_scope(client_id=another_client_id, client_roles_owner_id=client_id, roles=client_roles)
  238. # Get client roles assigned to client's scope
  239. keycloak_admin.get_client_roles_of_client_scope(client_id=another_client_id, client_roles_owner_id=client_id)
  240. # Remove client roles assigned to client's scope
  241. keycloak_admin.delete_client_roles_of_client_scope(client_id=another_client_id, client_roles_owner_id=client_id, roles=client_roles)
  242. # Get all ID Providers
  243. idps = keycloak_admin.get_idps()
  244. # Create a new Realm
  245. keycloak_admin.create_realm(payload={"realm": "demo"}, skip_exists=False)
  246. # Changing Realm
  247. keycloak_admin = KeycloakAdmin(realm_name="main", ...)
  248. keycloak_admin.get_users() # Get user in main realm
  249. keycloak_admin.realm_name = "demo" # Change realm to 'demo'
  250. keycloak_admin.get_users() # Get users in realm 'demo'
  251. keycloak_admin.create_user(...) # Creates a new user in 'demo'
  252. # KEYCLOAK UMA
  253. from keycloak import KeycloakOpenIDConnection
  254. from keycloak import KeycloakUMA
  255. keycloak_connection = KeycloakOpenIDConnection(
  256. server_url="http://localhost:8080/",
  257. realm_name="master",
  258. client_id="my_client",
  259. client_secret_key="client-secret")
  260. keycloak_uma = KeycloakUMA(connection=keycloak_connection)
  261. # Create a resource set
  262. resource_set = keycloak_uma.resource_set_create({
  263. "name": "example_resource",
  264. "scopes": ["example:read", "example:write"],
  265. "type": "urn:example"})
  266. # List resource sets
  267. resource_sets = uma.resource_set_list()
  268. # get resource set
  269. latest_resource = uma.resource_set_read(resource_set["_id"])
  270. # update resource set
  271. latest_resource["name"] = "New Resource Name"
  272. uma.resource_set_update(resource_set["_id"], latest_resource)
  273. # delete resource set
  274. uma.resource_set_delete(resource_id=resource_set["_id"])
  275. ```