Python Keycloak Get Roles and Groups of user

故事扮演 提交于 2019-12-25 01:54:17

问题


Using Key Cloak created groups and assigned roles to the groups. Than created the users and assigned the users to specific groups.

To access all this in my application I am using Python-Keycloak

As mentioned in github doc, using following code to access the user information.

from keycloak import KeycloakOpenID

keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
                    client_id="account",
                    realm_name="demo",
                    client_secret_key="my_secret_key")

config_well_know = keycloak_openid.well_know()

token = keycloak_openid.token("username", "password")
userinfo = keycloak_openid.userinfo(token['access_token'])

Getting following userinfo

{
    'family_name': 'Lastname', 
    'preferred_username': 'user_name', 
    'sub': 'some_key', 
    'given_name': 'Fistname', 
    'name': 'Firstname Lastname', 
    'email': 'email@example.com'
}

How can I access the group and roles information of the user.


回答1:


You need to use "KeycloakAdmin" class in the same library (python-keycloak):

from keycloak import KeycloakAdmin

admin = KeycloakAdmin(server_url='https://server-url',
                      username='username',
                      password='password',
                      realm_name='realm',
                      verify=True)

user_groups = admin.get_user_groups(user_id="user-id")

For use KeycloakAdmin, you will need of a user with access to "admin-cli".




回答2:


  1. Go to Keycloak, select you client -> Mapper -> Create.
  2. In a Mapper Type list select "Group Membership".
  3. In Token Claim Name field specify desired userinfo property name, e.g. "Groups".
  4. In Name field specify whatever you want for mapper name and click Save.
  5. Try again authenticating to Keycloak with your app. User groups should now be visible in userinfo JSON.



回答3:


Created one admin user for my realm. and inherit the class like this

from keycloak import KeycloakAdmin
from keycloak.exceptions import raise_error_from_response, KeycloakGetError

class CustomKeycloakAdmin(KeycloakAdmin):
    def get_user_group(self,user_name):
        USER_GROUP_URL = "admin/realms/{realm-name}/users/{user-id}/groups"
        params_path = {"user-id":self.get_user_id(user_name),"realm-name": self.realm_name}
        data_raw = self.connection.raw_get(USER_GROUP_URL.format(**params_path))
        return raise_error_from_response(data_raw, KeycloakGetError)

if __name__=="__main__":
    keycloak_admin = CustomKeycloakAdmin(server_url="http://localhost:8080/auth/",username='admin_user',password='admin_password',realm_name="my_realm",verify=True)
    user_group = keycloak_admin.get_user_group("user_name")


来源:https://stackoverflow.com/questions/49612535/python-keycloak-get-roles-and-groups-of-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!