I secured an application in Spring Boot using Keycloak and I'm trying to get the name of the current user logged in.
Following the answer of this question, I tried:
public Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) authentication.getPrincipal();
return kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
}
return null;
});
}
but with no luck. It gives me a warning about the unchecked cast, and it doesn't work!
How can I get the user logged in using Keycloak?