Kambei
Kambei

Reputation: 633

How to get the current logged in user in Spring Boot with Keycloak?

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?

Upvotes: 4

Views: 7301

Answers (1)

Kambei
Kambei

Reputation: 633

Using class KeycloakPrincipal only, gives the warning

Raw use of parameterized class 'KeycloakPrincipal'

but it works!

[...]
if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
    KeycloakPrincipal principal = (KeycloakPrincipal) authentication.getPrincipal();
    return principal.getName();
[...]

Upvotes: 3

Related Questions