0

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();
dur
  • 15,689
  • 25
  • 79
  • 125
Abhishek
  • 156
  • 1
  • 10
  • Does this answer your question? [Use Keycloak Spring Adapter with Spring Boot 3](https://stackoverflow.com/questions/74571191/use-keycloak-spring-adapter-with-spring-boot-3) – ch4mp Mar 20 '23 at 09:17

2 Answers2

0

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();
        }
Chetan Ahirrao
  • 1,454
  • 11
  • 16
  • 1
    Actually, it's not "I think", it's "it was a year ago". Adapters are not compatible with Boot 3 at all. https://stackoverflow.com/questions/74571191/use-keycloak-spring-adapter-with-spring-boot-3 – ch4mp Mar 20 '23 at 09:23
  • removed I think :) – Chetan Ahirrao Mar 20 '23 at 09:26
0
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);
Abhishek
  • 156
  • 1
  • 10