Package: python-keycloak-async
Python Keycloak AsyncFor review- seehttps://github.com/quangpq/python-keycloak-asyncpython-keycloak-asyncis a Python package providing access to the Keycloak API.InstallationVia Pypi Package:$ pip install python-keycloak-asyncManually$ python setup.py installDependenciespython-keycloak-async depends on:Python 3httpxaiofilespython-joseTests Dependenciestoxpytestpytest-asynciopytest-covwheelBug reportsPlease report bugs and feature requests athttps://github.com/quangpq/python-keycloak-async/issuesContributorsAgriness TeamMarcos PereiraMartin DevlinShon T. UrbasMarkus SpanierRemco KranenburgArminnjordrJosha InglisAlexEwan JoneLukas MartiniAdamaticsUsagefromkeycloakimportKeycloakOpenID# Configure clientkeycloak_openid=KeycloakOpenID(server_url="http://localhost:8080/auth/",client_id="example_client",realm_name="example_realm",client_secret_key="secret")# Close connectionawaitkeycloak_openid.aclose()# or using context managerasyncwithKeycloakOpenID(server_url=f"http://localhost:8080/",realm_name="example_client",client_id="example_realm",client_secret_key="secret",)askeycloak_openid:pass# Get WellKnownconfig_well_known=awaitkeycloak_openid.well_known()# Get Code With Oauth Authorization Requestauth_url=keycloak_openid.auth_url(redirect_uri="your_call_back_url",scope="email",state="your_state_info")# Get Access Token With Codeaccess_token=keycloak_openid.token(grant_type='authorization_code',code='the_code_you_get_from_auth_url_callback',redirect_uri="your_call_back_url")# Get Tokentoken=awaitkeycloak_openid.token("user","password")token=awaitkeycloak_openid.token("user","password",totp="012345")# Get token using Token Exchangetoken=awaitkeycloak_openid.exchange_token(token['access_token'],"my_client","other_client","some_user")# Get Userinfouserinfo=awaitkeycloak_openid.userinfo(token['access_token'])# Refresh tokentoken=awaitkeycloak_openid.refresh_token(token['refresh_token'])# Logoutawaitkeycloak_openid.logout(token['refresh_token'])# Get Certscerts=awaitkeycloak_openid.certs()# Get RPT (Entitlement)token=awaitkeycloak_openid.token("user","password")rpt=awaitkeycloak_openid.entitlement(token['access_token'],"resource_id")# Introspect RPTtoken_rpt_info=awaitkeycloak_openid.introspect(token['access_token'],rpt=rpt['rpt'],token_type_hint="requesting_party_token")# Introspect Tokentoken_info=awaitkeycloak_openid.introspect(token['access_token'])# Decode TokenKEYCLOAK_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n"+awaitkeycloak_openid.public_key()+"\n-----END PUBLIC KEY-----"options={"verify_signature":True,"verify_aud":True,"verify_exp":True}token_info=keycloak_openid.decode_token(token['access_token'],key=KEYCLOAK_PUBLIC_KEY,options=options)# Get permissions by tokentoken=awaitkeycloak_openid.token("user","password")awaitkeycloak_openid.load_authorization_config("example-authz-config.json")policies=awaitkeycloak_openid.get_policies(token['access_token'],method_token_info='decode',key=KEYCLOAK_PUBLIC_KEY)permissions=awaitkeycloak_openid.get_permissions(token['access_token'],method_token_info='introspect')# Get UMA-permissions by tokentoken=awaitkeycloak_openid.token("user","password")permissions=awaitkeycloak_openid.uma_permissions(token['access_token'])# Get UMA-permissions by token with specific resource and scope requestedtoken=awaitkeycloak_openid.token("user","password")permissions=awaitkeycloak_openid.uma_permissions(token['access_token'],permissions="Resource#Scope")# Get auth status for a specific resource and scope by tokentoken=awaitkeycloak_openid.token("user","password")auth_status=awaitkeycloak_openid.has_uma_access(token['access_token'],"Resource#Scope")# KEYCLOAK ADMINfromkeycloakimportKeycloakAdminfromkeycloakimportKeycloakOpenIDConnectionkeycloak_connection=KeycloakOpenIDConnection(server_url="http://localhost:8080/",username='example-admin',password='secret',realm_name="master",user_realm_name="only_if_other_realm_than_master",client_id="my_client",client_secret_key="client-secret",verify=True)keycloak_admin=KeycloakAdmin(connection=keycloak_connection)# Fetch admin tokenawaitkeycloak_admin.init_token()# Close connectionawaitkeycloak_admin.aclose()# or using context managerasyncwithKeycloakAdmin(connection=keycloak_connection)askeycloak_admin:pass# Add usernew_user=awaitkeycloak_admin.create_user({"email":"example@example.com","username":"example@example.com","enabled":True,"firstName":"Example","lastName":"Example"})# Add user and raise exception if username already exists# exist_ok currently defaults to True for backwards compatibility reasonsnew_user=awaitkeycloak_admin.create_user({"email":"example@example.com","username":"example@example.com","enabled":True,"firstName":"Example","lastName":"Example"},exist_ok=False)# Add user and set passwordnew_user=awaitkeycloak_admin.create_user({"email":"example@example.com","username":"example@example.com","enabled":True,"firstName":"Example","lastName":"Example","credentials":[{"value":"secret","type":"password",}]})# Add user and specify a localenew_user=awaitkeycloak_admin.create_user({"email":"example@example.fr","username":"example@example.fr","enabled":True,"firstName":"Example","lastName":"Example","attributes":{"locale":["fr"]}})# User countercount_users=awaitkeycloak_admin.users_count()# Get users Returns a list of users, filtered according to query parametersusers=awaitkeycloak_admin.get_users({})# Get user ID from usernameuser_id=awaitkeycloak_admin.get_user_id("username-keycloak")# Get Useruser=awaitkeycloak_admin.get_user("user-id-keycloak")# Update Userresponse=awaitkeycloak_admin.update_user(user_id="user-id-keycloak",payload={'firstName':'Example Update'})# Update User Passwordresponse=awaitkeycloak_admin.set_user_password(user_id="user-id-keycloak",password="secret",temporary=True)# Get User Credentialscredentials=awaitkeycloak_admin.get_credentials(user_id='user_id')# Get User Credential by IDcredential=awaitkeycloak_admin.get_credential(user_id='user_id',credential_id='credential_id')# Delete User Credentialresponse=awaitkeycloak_admin.delete_credential(user_id='user_id',credential_id='credential_id')# Delete Userresponse=awaitkeycloak_admin.delete_user(user_id="user-id-keycloak")# Get consents granted by the userconsents=awaitkeycloak_admin.user_consents(user_id="user-id-keycloak")# Send User Actionresponse=awaitkeycloak_admin.send_update_account(user_id="user-id-keycloak",payload=['UPDATE_PASSWORD'])# Send Verify Emailresponse=awaitkeycloak_admin.send_verify_email(user_id="user-id-keycloak")# Get sessions associated with the usersessions=awaitkeycloak_admin.get_sessions(user_id="user-id-keycloak")# Get themes, social providers, auth providers, and event listeners available on this serverserver_info=awaitkeycloak_admin.get_server_info()# Get clients belonging to the realm Returns a list of clients belonging to the realmclients=awaitkeycloak_admin.get_clients()# Get client - id (not client-id) from client by nameclient_id=awaitkeycloak_admin.get_client_id("my-client")# Get representation of the client - id of client (not client-id)client=awaitkeycloak_admin.get_client(client_id="client_id")# Get all roles for the realm or clientrealm_roles=awaitkeycloak_admin.get_realm_roles()# Get all roles for the clientclient_roles=awaitkeycloak_admin.get_client_roles(client_id="client_id")# Get client rolerole=awaitkeycloak_admin.get_client_role(client_id="client_id",role_name="role_name")# Warning: Deprecated# Get client role id from namerole_id=awaitkeycloak_admin.get_client_role_id(client_id="client_id",role_name="test")# Create client roleawaitkeycloak_admin.create_client_role(client_role_id='client_id',payload={'name':'roleName','clientRole':True})# Assign client role to user. Note that BOTH role_name and role_id appear to be required.awaitkeycloak_admin.assign_client_role(client_id="client_id",user_id="user_id",role_id="role_id",role_name="test")# Retrieve client roles of a user.awaitkeycloak_admin.get_client_roles_of_user(user_id="user_id",client_id="client_id")# Retrieve available client roles of a user.awaitkeycloak_admin.get_available_client_roles_of_user(user_id="user_id",client_id="client_id")# Retrieve composite client roles of a user.awaitkeycloak_admin.get_composite_client_roles_of_user(user_id="user_id",client_id="client_id")# Delete client roles of a user.awaitkeycloak_admin.delete_client_roles_of_user(client_id="client_id",user_id="user_id",roles={"id":"role-id"})awaitkeycloak_admin.delete_client_roles_of_user(client_id="client_id",user_id="user_id",roles=[{"id":"role-id_1"},{"id":"role-id_2"}])# Get the client authorization settingsclient_authz_settings=awaitkeycloak_admin.get_client_authz_settings(client_id="client_id")# Get all client authorization resourcesclient_resources=awaitkeycloak_admin.get_client_authz_resources(client_id="client_id")# Get all client authorization scopesclient_scopes=awaitkeycloak_admin.get_client_authz_scopes(client_id="client_id")# Get all client authorization permissionsclient_permissions=awaitkeycloak_admin.get_client_authz_permissions(client_id="client_id")# Get all client authorization policiesclient_policies=awaitkeycloak_admin.get_client_authz_policies(client_id="client_id")# Create new groupgroup=awaitkeycloak_admin.create_group({"name":"Example Group"})# Get all groupsgroups=awaitkeycloak_admin.get_groups()# Get groupgroup=awaitkeycloak_admin.get_group(group_id='group_id')# Get group by namegroup=awaitkeycloak_admin.get_group_by_path(path='/group/subgroup',search_in_subgroups=True)# Function to trigger user sync from providerawaitkeycloak_admin.sync_users(storage_id="storage_di",action="action")# Get client role id from namerole_id=awaitkeycloak_admin.get_client_role_id(client_id=client_id,role_name="test")# Assign client role to user. Note that BOTH role_name and role_id appear to be required.awaitkeycloak_admin.assign_client_role(client_id=client_id,user_id=user_id,role_id=role_id,role_name="test")# Assign realm roles to userawaitkeycloak_admin.assign_realm_roles(user_id=user_id,roles=realm_roles)# Assign realm roles to client's scopeawaitkeycloak_admin.assign_realm_roles_to_client_scope(client_id=client_id,roles=realm_roles)# Get realm roles assigned to client's scopeawaitkeycloak_admin.get_realm_roles_of_client_scope(client_id=client_id)# Remove realm roles assigned to client's scopeawaitkeycloak_admin.delete_realm_roles_of_client_scope(client_id=client_id,roles=realm_roles)another_client_id=awaitkeycloak_admin.get_client_id("my-client-2")# Assign client roles to client's scopeawaitkeycloak_admin.assign_client_roles_to_client_scope(client_id=another_client_id,client_roles_owner_id=client_id,roles=client_roles)# Get client roles assigned to client's scopeawaitkeycloak_admin.get_client_roles_of_client_scope(client_id=another_client_id,client_roles_owner_id=client_id)# Remove client roles assigned to client's scopeawaitkeycloak_admin.delete_client_roles_of_client_scope(client_id=another_client_id,client_roles_owner_id=client_id,roles=client_roles)# Get all ID Providersidps=awaitkeycloak_admin.get_idps()# Create a new Realmawaitkeycloak_admin.create_realm(payload={"realm":"demo"},skip_exists=False)# Changing Realmkeycloak_admin=KeycloakAdmin(realm_name="main",...)awaitkeycloak_admin.get_users()# Get user in main realmkeycloak_admin.realm_name="demo"# Change realm to 'demo'awaitkeycloak_admin.get_users()# Get users in realm 'demo'awaitkeycloak_admin.create_user(...)# Creates a new user in 'demo'# KEYCLOAK UMAfromkeycloakimportKeycloakOpenIDConnectionfromkeycloakimportKeycloakUMAkeycloak_connection=KeycloakOpenIDConnection(server_url="http://localhost:8080/",realm_name="master",client_id="my_client",client_secret_key="client-secret")keycloak_uma=KeycloakUMA(connection=keycloak_connection)# Fetch admin tokenawaitkeycloak_uma.init_token()# Close connectionawaitkeycloak_uma.aclose()# or using context managerasyncwithKeycloakUMA(connection=keycloak_connection)askeycloak_uma:pass# Create a resource setresource_set=awaitkeycloak_uma.resource_set_create({"name":"example_resource","scopes":["example:read","example:write"],"type":"urn:example"})# List resource setsresource_sets=[xasyncforxinkeycloak_uma.resource_set_list()]# get resource setlatest_resource=awaitkeycloak_uma.resource_set_read(resource_set["_id"])# update resource setlatest_resource["name"]="New Resource Name"awaitkeycloak_uma.resource_set_update(resource_set["_id"],latest_resource)# delete resource setawaitkeycloak_uma.resource_set_delete(resource_id=resource_set["_id"])