Not able to get KeycloakPrincipal when using keycloak spring boot integrated with keycloak spring security adapter

I am not able to get KeycloakPrincipal, when using Keycloak with Spring Security. How do I solve this?

Check if your user principal is an instance of KeycloakPrincipal and than cast it.
Without much information or code examples that’s the only thing I can give you.

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
    .currentRequestAttributes()).getRequest();
KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) request.getUserPrincipal();

I use it like this:

@RestController
@RequestMapping("/protected")
class ProtectedController {
    var logger: Logger = LoggerFactory.getLogger(ProtectedController::class.java)

    // @Autowired
    // private lateinit var auth: KeycloakSecurityContext

    @GetMapping("/message")
    fun saySomething(authToken: KeycloakAuthenticationToken, message: String): String {
        val principal = authToken.principal as KeycloakPrincipal<KeycloakSecurityContext>

        return "Psst: (wisper) $message -> ${principal.name}"
    }
}

(In Kotlin but you get the idea…)