Obtaining user roles in servlet application using keycloak

强颜欢笑 提交于 2019-11-28 03:56:41

问题


I'm using keycloak to protect my servlet. I have to add new roles and assign them to users dynamically. It works in keycloak using admin API, but I can't figure out how to obtain the roles for specific user in a servlet.

I tried this solution, but I get empty set:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
...

KeycloakSecurityContext context = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext((RefreshableKeycloakSecurityContext) context);
...
}

回答1:


@Shiva's answer did not work for me. getRealmAccess() was returning null. we had to use the following:

KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();

String clientId = "securesite";
principal.getKeycloakSecurityContext().getToken().getResourceAccess(clientId).getRoles();



回答2:


If the servlet is protected by keyclaok then you can use the following API to get the KeycloakSecurityContext and then access the Set of roles to modify it.

KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();

 principal.getKeycloakSecurityContext().getToken().getRealmAccess().getRoles().add("Test-Role");

A sample servlet request might look like this.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    @SuppressWarnings("rawtypes")
    KeycloakPrincipal principal = (KeycloakPrincipal)request.getUserPrincipal();
    if (principal != null) {
        //user has a valid session, we can assign role on the fly like this
        principal.getKeycloakSecurityContext().getToken().getRealmAccess().getRoles().add("Test-Role");

        }
}


来源:https://stackoverflow.com/questions/29014894/obtaining-user-roles-in-servlet-application-using-keycloak

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