Extract Keycloak Principal in spring boot 3 using oauth

1.2k Views Asked by At

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();
2

There are 2 best solutions below

0
Abhishek Kotalwar On BEST ANSWER
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);
2
Chetan Ahirrao On

Keycloak's legacy API is already deprecated. You don't need KeycloakAuthenticationToken for extracting principal. Use standard spring oauth2 code like

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication !=null) {
          Principal principal = (Principal) authentication.getPrincipal();
        }