7

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);
...
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ilja Sucharev
  • 201
  • 1
  • 2
  • 8

2 Answers2

7

@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
    That's correct if in keycloak.json the option __"use-resource-role-mappings" : true__ ist set – Boomer Oct 31 '17 at 09:13
3

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");

        }
}
Shiva
  • 6,677
  • 4
  • 36
  • 61
  • 4
    Adding roles to the Keycloak security context is a bad idea. These roles will only be present until the token is refreshed. – Scott Jan 14 '16 at 22:02