aksappy aksappy - 1 year ago 221
Java Question

Fetch Logged In Username in a webapp secured with Keycloak

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

etc. But none of them are able to give me the required details.

Answer Source

You get all user information from the security context.


public class Greeter {

  SecurityContext sc;

  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