Fetch Logged In Username in a webapp secured with Keycloak

aksappy picture aksappy · Aug 6, 2015 · Viewed 17.6k times · Source

I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?

I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.

Answer

sebplorenz picture sebplorenz · Aug 7, 2015

You get all user information from the security context.

Example:

public class Greeter {

  @Context
  SecurityContext sc;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public String sayHello() {

    // this will set the user id as userName
    String userName = sc.getUserPrincipal().getName();

    if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
      KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>)  sc.getUserPrincipal();

      // this is how to get the real userName (or rather the login name)
      userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
    }

    return "{ message : \"Hello " + userName + "\" }";
}

For the security context to be propagated you have to have a security domain configured as described in the: JBoss/Wildfly Adapter configuration