Unable to define properties which start with keycloak - java

Unable to define properties which start with keycloak. keycloak-spring-boot-starter starter jar fails to load the properties if it observes keycloak properties which aren't known to the jar. The issue gets resolved if we prefix "sso" to the properties, is there a way to avoid this error even when keeping the keycloak prefixes.
keycloak.admin.username=
keycloak.admin.password=
sso.keycloak.admin.username=
sso.keycloak.admin.password=
this is the error seen with Spring Boot 2.5.0 and Keycloak 13.0.0
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
... 21 more
Caused by: java.lang.NullPointerException
at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterAtOffsetOf(HttpSecurity.java:2654)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterAfter(HttpSecurity.java:2645)
at org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter.configure(KeycloakWebSecurityConfigurerAdapter.java:123)
at com.foo.config.KeycloakSecurityConfig.configure(KeycloakSecurityConfig.java:36)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:217)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:315)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:93)
at com.foo.config.KeycloakSecurityConfig$$EnhancerBySpringCGLIB$$501f46fb.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:338)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:300)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:38)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:127)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)

This error was introduced in version 5.5.0 of Spring Security which comes with Spring Boot 2.5.0.
This is happening because KeyCloak adds two filters successively after another, like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
...
.addFilterAfter(keycloakSecurityContextRequestFilter(), SecurityContextHolderAwareRequestFilter.class)
.addFilterAfter(keycloakAuthenticatedActionsRequestFilter(), KeycloakSecurityContextRequestFilter.class)
...
}
And there's a bug right now in which the custom filter order is not being persisted, thus resulting in a NullPointerException when trying to add a filter relative to another custom filter recently added.
What I advise you to do right now is to use a lower version of Spring Boot, like 2.4.x until the issue in GitHub gets resolved.

From the Keycloak code it seems they have hardwired the properties to specific properties only.
From KeycloakSpringBootProperties
/* this is a dummy property to avoid re-rebinding problem with
property keycloak.config.resolver
when using spring cloud - see KEYCLOAK-2977 */
From their code, its seems we can make use of a workaround they have to include additional properties.
But to do that we have to add 'config' in it.
keycloak.config.admin.username=asd
keycloak.config.admin.password=sss

Related

Spring 6 PostGIS integration

This question was migrated from Geographic Information Systems Stack Exchange because it can be answered on Stack Overflow.
Migrated 14 days ago.
I have been trying to port an existing application using PostGIS from Spring 5 to Spring 6.
I get an error saying that org.hibernate.spatial.dialect.postgis.PostgisDialect is not more available:
Task :packages:discover-app-back-api:bootRun FAILED
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.spatial.dialect.postgis.PostgisDialect] as strategy [org.hibernate.dialect.Dialect]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.spatial.dialect.postgis.PostgisDialect]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.spatial.dialect.postgis.PostgisDialect
Spring boot 3.0.2
Spring security 6.0.1
Hibernate 6.1.6
Indeed, this class is no more available in the version 6.X.
What configuration should I use?
You no longer need to specify the dialect:
The PostgisDialect class was first replaced by PostgisPG9xDialect / PostgisPG10Dialect classes, but now these are also deprecated ("A SpatialDialect is no longer required.").
So the correct dialect is the default (org.hibernate.dialect.PostgreSQLDialect).
But since it is the default it shouldn't be necessary to specify it in your Spring-Boot application, both the default driver and dialect can be derived from what you specify in spring.datasource.url

NoClassDefFoundError for ClientConnectionManager

I am trying to consume a soap webservice and included the relative dependency in gradle file as
implementation('org.springframework.boot:spring-boot-starter-web-services') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
along with Jaxb dependencies. This code works absolutely fine in my local and I am able to retrieve the results from the service, but when I deploy this code to Openshift, I am getting below error:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com..abc.xyz.AccountServiceClient]: Factory method 'accountServiceClient' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/conn/ClientConnectionManager
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.22.jar!/:5.3.22]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.22.jar!/:5.3.22]
... 69 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/apache/http/conn/ClientConnectionManager
at com.discover.card.collections.aprapi.config.WebServiceConfig.httpComponentsMessageSender(WebServiceConfig.java:43) ~[classes!/:na]
at com.discover.card.collections.aprapi.config.WebServiceConfig.accountServiceClient(WebServiceConfig.java:31) ~[classes!/:na]
at com.discover.card.collections.aprapi.config.WebServiceConfig$$EnhancerBySpringCGLIB$$79bdd48b.CGLIB$accountServiceClient$1(<generated>) ~[classes!/:na]
I have tried to add the dependency for HttpClient and
implementation("org.apache.httpcomponents:httpclient:4.5.3")
implementation "org.apache.cxf:cxf-rt-transports-http-hc:3.4.2"
but it is still not working.
Tried searching as well, but didn't see anybody else facing similar scenario where it works fine in local, but throws error while deploying in openshift.
I am using same yaml profile for both local and dev, so that should also not be the issue.
Pls advise what else can I look out for?

Overriding Hibernate ConnectionProvider in Spring Boot 2.1

I am upgrading a kotlin Spring Boot 1.x application to use Spring Boot 2.1.6
Previously I used EntityManagerFactoryBeanCallback to set the hibernate.connection.provider_class to our custom implementation of ConnectionProvider. This was deprecated and removed in spring boot 2.0 and 2.1 respectively.
I am now attempting to use a HibernatePropertiesCustomizer
#Bean
fun hibernatePropertiesCustomizer() = HibernatePropertiesCustomizer {
it["hibernate.connection.provider_class"] = ScopedConnectionProvider::class.java.name
}
The application throws an error now:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by:
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by:
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
If I comment out the it["hibernate.connection.provider_class"] = ScopedConnectionProvider::class.java.name line everything works except obviously the custom ConnectionProvider
For reference I am using the ScopedConnectionProvider to enable our multitenancy by setting a variable on each connection representing the customers scope ID. Any alternate solution that allows me to run a SET #scope_id = ? query on every connection would also be fine.
Relevant version information:
Spring Boot: 2.1.6
Spring: 5.1.8
Hibernate: 5.3.10
Kotlin: 1.3.21
It turns out that the Datasource was not being injected into my ScopedConnectionProvider correctly anymore. I changed it so that I was inheriting from DatasourceConnectionProviderImpl instead of implementing my own ConnectionProvider from scratch. This seems to have removed the need to specify the dialect.

ClassLoader classcastexception with activemq client

I have been struggling with this problem for a while now, decided to ask the community, hoping to get some hints/answers.
I am using tomcat 7.0.54 as my J2EE container which has a WAR deployed with dependency on activemq-all.
Along with the above, I'm also placing a jar in the classpath to register a listener programmatically, by implementing the ServletContainerInitializer interface. This initializes a simple implementation of an active mq client, JvmMessageProducerImpl (I have activemq-client as a dependency in the pom).
With the above setup, when i try to start tomcat, i get the below exception. It seems that instead of loading the classes independently, the listener which is called when the web application starts, is finding an existing instance of TcpTransportFactory and throwing the ClassCastException. I have read the classloader manual for tomcat multiple times, and my understanding is that each of the war files should have independent Class loaders - but dont completely understand why the exception is being thrown?
javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [tcp]
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36)
at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:317)
at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:330)
at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:251)
at com.monitoreverywhere.jvmmon.mq.JvmMessageProducerImpl.setup(JvmMessageProducerImpl.java:66)
at com.monitoreverywhere.jvmmon.mq.JvmMessageProducerImpl$Runner.run(JvmMessageProducerImpl.java:163)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.io.IOException: Transport scheme NOT recognized: [tcp]
at org.apache.activemq.util.IOExceptionSupport.create(IOExceptionSupport.java:27)
at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:181)
at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:63)
at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:315)
... 5 more
Caused by: java.lang.ClassCastException: org.apache.activemq.transport.tcp.TcpTransportFactory cannot be cast to org.apache.activemq.transport.TransportFactory
at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:178)
... 7 more

Initialize Hibernate SessionFactory in a EJB mdb?

I am trying to deploy an MDB in WAS 8.5. The session Factory is being initialized in ejbCreate method. When I try to deploy the application ejb loads successfully and then it shuts down the Queue Activation and gives the following exceptions-
I am not using any framework or MAven for built so all the jars and config files have been added to the classpath as in a Standalone Java Application.
Here are the Hibernate and JAVAEE Jars I am using-
antlr-2.7.7
c3p0-0.9.1
commons-collections-3.2.1
commons-logging-api-1.1.3
dom4j-1.6.1
hibernate-c3p0-4.1.5.Final
hibernate-commons-annotations-4.0.1.Final
hibernate-core-4.1.5.Final
hibernate-entitymanager-4.1.5.Final
hibernate-envers-4.1.5.Final
hibernate-jpa-2.0-api-1.0.1.Final
javassist-3.15.0GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final
jms-1.1
log4j-1.2.15
MySQL-connector-java-5.1.22
slf4j-api-1.6.1
javaee.jar
javaee-api-6.0
Here is the exception stacktrace from system logs
EJB threw an unexpected (non-declared) exception during invocation of method "onMessage".Exception data:
javax.ejb.EJBException: MDB PostConstruct failure; nested exception is:
java.lang.Exception: See nested Throwable
at com.ibm.ejs.container.util.ExceptionUtil.EJBException(ExceptionUtil.java:472)
at com.ibm.ejs.container.MessageDrivenBeanO.initialize(MessageDrivenBeanO.java:427)
at com.ibm.ejs.container.BeanOFactory.create(BeanOFactory.java:147)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1238)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1356)
at com.ibm.ejs.container.activator.UncachedActivationStrategy.atActivate
(UncachedActivationStrategy.java:88)
at com.ibm.ejs.container.activator.Activator.preInvokeActivateBean(Activator.java:615)
at com.ibm.ejs.container.EJSContainer.preInvokeActivate(EJSContainer.java:4205)
at com.ibm.ejs.container.EJSContainer.preInvokeMdbActivate(EJSContainer.java:3709)
at com.ibm.ejs.container.MessageEndpointHandler.beforeDelivery
(MessageEndpointHandler.java:1449)
at com.ibm.ejs.container.MessageEndpointHandler.invokeMessageEndpointMethod
(MessageEndpointHandler.java:866)
at com.ibm.ejs.container.MessageEndpointHandler.invoke(MessageEndpointHandler.java:832)
at $Proxy50.beforeDelivery(Unknown Source)
at com.ibm.mq.connector.inbound.AbstractWorkImpl.run(AbstractWorkImpl.java:188)
at com.ibm.ejs.j2c.work.WorkProxy.run(WorkProxy.java:608)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1783)
Caused by: java.lang.Exception: See nested Throwable
at com.ibm.ejs.container.util.ExceptionUtil.EJBException(ExceptionUtil.java:470)
... 15 more
Caused by: java.lang.NoClassDefFoundError: org.hibernate.HibernateException
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:85)
at java.lang.J9VMInternals.initialize(J9VMInternals.java:162)
at com.hps.superenrollment.ejbmodule.SuperEnrollmentRequestMDB.ejbCreate
(SuperEnrollmentRequestMDB.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor
(InterceptorProxy.java:232)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed
(InvocationContextImpl.java:559)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doLifeCycle
(InvocationContextImpl.java:273)
at com.ibm.ejs.container.MessageDrivenBeanO.initialize(MessageDrivenBeanO.java:411)
Please help me as I am completely lost on what is going wrong here .
The NoClassDefFoundError indicates that some Hibernate class is not in your class-path. Are you sure you have all dependency jars in your classpath (including the jars which are needed at runtime)?
The exception indicating that you should use a PostConstructor method instead of the bean class constructor indicates that you should use the ejbCreate() method. This is the recommended location to initialise and load dependencies of your MDB as it is called by one single thread of the ejb container and ensures that the MDB has been fully constructed before you execute the configuration in the ejbCreate(). It is somewhat similar to the init method in a servlet which is also guaranteed to be called single threaded by the servlet container.

Categories