How to get userinfo in springboot using keycloak?

10,308
        KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();        
        KeycloakPrincipal principal=(KeycloakPrincipal)token.getPrincipal();
        KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
        AccessToken accessToken = session.getToken();
        username = accessToken.getPreferredUsername();
        emailID = accessToken.getEmail();
        lastname = accessToken.getFamilyName();
        firstname = accessToken.getGivenName();
        realmName = accessToken.getIssuer();            
        Access realmAccess = accessToken.getRealmAccess();
        roles = realmAccess.getRoles();

You can make use of the above code snippet to get the first and the last name This is from 2.4.0

Share:
10,308
LogronJ
Author by

LogronJ

Goma2x no jutsu

Updated on June 24, 2022

Comments

  • LogronJ
    LogronJ almost 2 years

    I was able to get the username by using:

    @Autowired
     private HttpServletRequest request;
     Principal user = request.getUserPrincipal();
     mqMessage.setUserName(user.getName());
    

    But I want to get the firstName & lastName of the user logged in. How can i get the ff. userinfo using SpringBoot keycloak adapter?

  • Yamen Nassif
    Yamen Nassif about 2 years
    auth is always null for me
  • immino
    immino almost 2 years
    @YamenNassif you must be authenticated for getting Authentication from SecurityContextHolder. Maybe check your spring security config?