spring-bootoauth-2.0keycloakspring-security-rest

Extract Keycloak Principal in spring boot 3 using oauth


is there any way to extract Keycloak Principal in spring boot 3 using oauth?

With older version we accessed like below,

 KeycloakAuthenticationToken authentication;
  try {
     authentication =
             (KeycloakAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
  } catch (ClassCastException exception) {
     throw new UnauthorizedException("Missing token");
  }
  Principal principal = (Principal) authentication.getPrincipal();

Solution

  • public final static String TOKEN_CLAIM_NAME = "preferred_username";                                                                                                  
    Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
    Map<String, Object> attributes = Collections.emptyMap();
    attributes = ((JwtAuthenticationToken) authToken).getTokenAttributes();
    String userName = (String) attributes.get(TOKEN_CLAIM_NAME);