Environment:
- Jboss7.2
- Keycloak 6.0.1
- Java 11
I am trying to cast Principal to get Keycloak user information, but I receive a ClassCastException. WebFilter and WebServlet are in different maven modules.
org.keycloak.KeycloakPrincipal is in unnamed module of loader '[email protected]' @4d7642f0; org.keycloak.KeycloakPrincipal is in unnamed module of loader 'deployment.app.ear' @4d7682a1
Error log
cast: java.lang.ClassCastException:
class org.keycloak.KeycloakPrincipal cannot be cast to class org.keycloak.KeycloakPrincipal
(org.keycloak.KeycloakPrincipal is in unnamed module of loader '[email protected]' @4d7642f0; org.keycloak.KeycloakPrincipal is in unnamed module of loader 'deployment.app.ear' @4d7682a1
...
pom.xml (root)
...
<modules>
<module>app-back</module> <!--where webservlet is-->
<module>app-ejb</module> <!--where webfilter is-->
<module>app-ear</module>
</modules>
...
WebFilter CAST KO
@WebFilter(filterName = "Filter", urlPatterns = "/*")
public class FilterPrincipal implements Filter {
...
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException, ServletException {
...
HttpServletRequest sReq = ((HttpServletRequest) req);
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) principal;//error
KeycloakSecurityContext keycloakSecurityContext = kp.getKeycloakSecurityContext();
AccessToken token = keycloakSecurityContext.getToken();
writer.println("username = " + token.getPreferredUsername());
...
chain.doFilter(req, resp);
}
...
**WebServlet CAST OK**
@WebServlet(urlPatterns = "/principal")
public class PrincipalInfoServlet extends HttpServlet {
...
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
...
Principal principal = request.getUserPrincipal();
if (principal != null) {
...
// API keycloak
if (principal instanceof KeycloakPrincipal<?>) {
writer.println("--------------------------------");
writer.println("Informació del token de keycloak:");
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) principal;//OK
KeycloakSecurityContext keycloakSecurityContext = kp.getKeycloakSecurityContext();
...
I found a workaround by moving webservlet to maven modul app-back so the KeycloakPrincipals are in the same module.