Spring Security OAuth2 - Unable to start Spring Boot App if configured with multiple external Auth Servers and failed to connect to one of them - spring-boot

Background :
Configure Spring Boot Application to support Multiple External Authorization Servers
Example of application.properties :
#First Authorization Server
spring.security.oauth2.client.registration.my_okta_account.client-id=<client id>
spring.security.oauth2.client.registration.my_okta_account.client-secret=<client secret>
spring.security.oauth2.client.provider.my_okta_account.issuer-uri=<okta issuer>
#Second Authorization Server
spring.security.oauth2.client.registration.my_azure_ad.client-id=<client id>
spring.security.oauth2.client.registration.my_azure_ad.client-secret=<client secret>
spring.security.oauth2.client.provider.my_azure_ad.issuer-uri=<azure ad issuer>
Problem Description :
At startup time Spring Boot will try to create a clientRegistrationRepository Bean based on the configuration info in the properties file for each Authorization Server and try to establish rest connection with it.
If Connection to External Authorization Server failed, Application will fail to start.
Error :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of
This is caused by : Caused by: java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of "<azure ad issuer>" at org.springframework.security.oauth2.client.registration.ClientRegistrations.getBuilder(ClientRegistrations.java:220) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1] at org.springframework.security.oauth2.client.registration.ClientRegistrations.fromIssuerLocation(ClientRegistrations.java:144) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1] at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getBuilderFromIssuerIfPossible(OAuth2ClientPropertiesRegistrationAdapter.java:83) ~[spring-boot-autoconfigure-2.4.5.jar:2.6.3]
This is caused by Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "< azure ad issuer >/.well-known/openid-configuration": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) ~[spring-web-5.3.6.jar:5.3.6] at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:670) ~[spring-web-5.3.6.jar:5.3.6] at org.springframework.security.oauth2.client.registration.ClientRegistrations.lambda$oidc$0(ClientRegistrations.java:155) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1]
This is a snippet of the method in org.springframework.security.oauth2.client.registration.ClientRegistrations that failed :
private static Supplier<ClientRegistration.Builder> oidc(URI issuer) {
// #formatter:off
URI uri = UriComponentsBuilder.fromUri(issuer)
.replacePath(issuer.getPath() + OIDC_METADATA_PATH)
.build(Collections.emptyMap());
// #formatter:on
return () -> {
RequestEntity<Void> request = RequestEntity.get(uri).build();
Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
OIDCProviderMetadata metadata = parse(configuration, OIDCProviderMetadata::parse);
ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer.toASCIIString())
.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
if (metadata.getUserInfoEndpointURI() != null) {
builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
}
return builder;
};
}
ClientRegistrations.java can be found here : https://github.com/spring-projects/spring-security/blob/5.6.x/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistrations.java
The Line that failed is : Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
Disclaimer :
As you might noticed this is a Certificate Exception and can easily be recovered by importing the root CA for <azure ad issuer>
Question :
Is there a way to suppress this error and force Spring Boot App to start even if the configuration of one of the Authorization Servers failed to create the 'clientRegistrationRepository'?
I tried to use Spring Lazy Initialization at the level of the Controller which depends on 'clientRegistrationRepository' Bean, but even if the controller is not yet initialized 'WebMvcAutoConfiguration' will try to instantiate the 'clientRegistrationRepository'
Error : org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setClientRegistrationRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of < azure ad issuer >
My goal here is to successfully start the Spring Boot Application even if the connection to one of the External Authorization Server is not working.

Related

Sailpoint iiq installatin I am facing BeanCreation Exception

WARN main springframework.context.support.ClassPathXmlApplicationContext:551 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'versionChecker' defined in class path resource [configBeans.xml]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Unable to check IdentityIQ database version: Cannot create JDBC driver of class '' for connect URL 'null'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'versionChecker' defined in class path resource [configBeans.xml]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Unable to check IdentityIQ database version: Cannot create JDBC driver of class '' for connect URL 'null'

Why creating been in Spring occurs with error?

Hello I am creating program which will communicate and send information using channel. When I run program it doesn't work.
Errors:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-05-02 13:47:37.938 ERROR 12584 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloWorldQueueProducer' defined in file [C:\workspace\target\classes\edu\producer\HelloWorldQueueProducer.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jmsTemplate' defined in class path resource [org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration$JmsTemplateConfiguration.class]: Unsatisfied dependency expressed through method 'jmsTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jmsConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration$SimpleConnectionFactoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jms.connection.CachingConnectionFactory]: Factory method 'cachingJmsConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Unable to create ActiveMQConnectionFactory
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.5.jar:5.3.5]
#Component
#RequiredArgsConstructor
public class HelloWorldQueueProducer {
private final JmsTemplate jmsTemplate;
#Scheduled(fixedRate = 2000)
public void sendHello() {
HelloMessage message = HelloMessage.builder()
.id(HelloMessage.nextId())
.createdAt(LocalDateTime.now())
.message("Hello world!")
.build();
jmsTemplate.convertAndSend(JmsConfig.QUEUE_HELLO_WORLD, message);
System.out.println("HelloWorldQueueProducer.sendHello - sent message: " + message);
}
}
Not quite sure about it, but have you defined the necessary properties in your application.properties? You need to set them like this i. e.
spring.artemis.mode=native
spring.artemis.host=localhost
spring.artemis.port=61616
spring.artemis.user=developer
spring.artemis.password=developer
jms.queue.destination=myqueue
Otherwise the autoconfiguration of spring boot wouldn't bootstrap the necessary beans. I had this problem once.

Spring boot application gives "unable to start tomcat" exception with spring-boot-starter-actuator

I had my spring-boot application, with spring-boot-starter-web, then I added spring-boot-starter-actuator to gradle file. There is no compilation error. But when i try to run the server it gives the following exception.
my build.gradle content (only the main ones included )
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
} ...........
compile "org.springframework.boot:spring-boot-starter-actuator"
compile group: 'io.micrometer', name: 'micrometer-registry-prometheus', version: '1.1.3' .........
my application.properties content
server.port = 2128
spring.couchbase.env.timeouts.connect=10000
spring.couchbase.env.timeouts.query=180000
spring.couchbase.env.timeouts.view=20000
spring.couchbase.bootstrap-hosts=localhost
spring.couchbase.bucket.name=localdb
spring.couchbase.bucket.password=*****
spring.data.couchbase.repositories.type=auto
spring.data.couchbase.auto-index=true
server.compression.enabled=true
server.compression.mime-types=application/json,text/plain
spring.servlet.multipart.enabled=true
spring.servlet.multipart.maxFileSize=50MB
spring.servlet.multipart.maxRequestSize=50MB
my Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Gives the following exception while starting the server.
org.springframework.context.ApplicationContextException: Unable to start web server;
nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource
WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource
org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 1;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthIndicatorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed
Any helpful hints?
I was finally able to start the application after I turned off default health checks via the following entry in application.properties file
management.health.defaults.enabled=false

Springboot Oauth2 : org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator$UnauthorizedException

I am trying to implement a fully functional Spring-boot oauth2. I manage to implement a login with success credential, I get the proper response with access_token and refresh_token, using /oauth/token
Using correct username and password
{
"access_token": "b8c45984-c573-4837-9ef6-6896f308a286",
"token_type": "bearer",
"refresh_token": "48145463-830e-4467-ab89-587bda6b32de",
"expires_in": 43199,
"scope": "read write"
}
and if i use a wrong username it give me a proper error, which i am happy about;
Wrong Username:
{error: "unauthorized", error_description: "No value present"}
error
:
"unauthorized"
error_description
:
"No value present"
but the problem comes when i use correct username and incorrect password; i get the below error
2018-05-28 14:47:25.264 WARN 6604 --- [nio-8088-exec-2] .c.j.MappingJackson2HttpMessageConverter :
Failed to evaluate Jackson serialization for type [class org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator$UnauthorizedException]:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Serializer':
BeanPostProcessor before instantiation of bean failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource
[org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]:
Factory method 'transactionAdvisor' threw exception;
nested exception is java.lang.NullPointerException

UnsatisfiedDependencyException by Maven Packed war but not Intellij IDE why?

i am using Intellij IDE for my springboot project, while running my spring boot project it works fine. but when i create a war with mvn package and run with java -jar project.war it throwing the following error
Warning
2018-05-23 11:05:08.635 WARN 13025 --- [ main]
ationConfigEmbeddedWebApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name HibernateJpaAutoConfiguration':
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource
[com/myproject/config/DefaultDataSource.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.mchange.v2.c3p0.ComboPooledDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.ExceptionInInitializerError
Exception
Error starting ApplicationContext. To display the auto-configuration
report re-run your application with 'debug' enabled.
2018-05-23 11:05:10.854 ERROR 13025 --- [ main]
o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/myproject/config/DefaultDataSource.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mchange.v2.c3p0.ComboPooledDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.ExceptionInInitializerError
Code
#Configuration
public class DefaultDataSource {
#Autowired
DataBaseCreds dataBaseCreds;
#Bean
#Primary
public ComboPooledDataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(dataBaseCreds.getDB_DRIVER());
} catch (PropertyVetoException e) {
}
dataSource.setJdbcUrl(dataBaseCreds.getDB_URL());
dataSource.setUser(dataBaseCreds.getDB_USERNAME());
dataSource.setPassword(dataBaseCreds.getDB_PASSWORD());
dataSource.setMaxPoolSize(200);
return dataSource;
}
}
Sorry guys my mistake there were two versions of c3p0 libraries packed war file /WEB-INF/lib removed one works like charm - Thanks for reading

Resources