Obtaining user roles in servlet application using keycloak

后端 未结 2 484
傲寒
傲寒 2020-12-19 09:42

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

相关标签:
2条回答
  • 2020-12-19 10:19

    @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();
    
    0 讨论(0)
  • 2020-12-19 10:25

    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");
    
            }
    }
    
    0 讨论(0)
提交回复
热议问题