Fetch Logged In Username in a webapp secured with Keycloak

前端 未结 5 628
轻奢々
轻奢々 2020-12-14 18:11

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, nee

5条回答
  •  不知归路
    2020-12-14 18:54

    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 kp = (KeycloakPrincipal)  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

提交回复
热议问题