Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
Kambei Avatar asked Oct 14 '25 06:10

Kambei


1 Answers

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();
[...]
like image 154
Kambei Avatar answered Oct 16 '25 21:10

Kambei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!