1

I'm working on a Spring Boot project, and I'm trying to enable self-signed SSL on it.
So far I have done the following:

With JRE keytool I have made a .p12 file in command line:

keytool -genkeypair -alias theblog -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore theblog.p12 -validity 3650 

I have set a password and answer the following questions (First name, Last name, company, etc.). I have let the State and the City "UNKNOWN".

Then I have copied the generated theblog.p12 file to the src/main/resources/keystore folder.

In the pom.xml I use this dependency:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

My application.yml looks like:

server:
    ssl:
        key-store-type: PKCS12
        key-store: src/main/resources/keystore/theblog.p12
        key-alias: theblog
        key-store-password: ********
        trust-store: src/main/resources/keystore/theblog.p12
        trust-store-password: ********
        enabled: true

I use this .p12 file as trust store as well as a Baeldung tutorial suggested:
"We need to create a trust store. As we have generated a PKCS12 file, we can use the same as the trust store."

Then I have created an SslConfig class:

package hu.hazazs.blog.config;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class SslConfig {
    @Value("${server.ssl.trust-store}")
    private Resource keyStore;
    @Value("${server.ssl.trust-store-password}")
    private String keyStorePassword;
    @Bean
    public RestTemplate restTemplate() throws Exception {
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder()
                .loadTrustMaterial(keyStore.getURL(),keyStorePassword.toCharArray())
                    .build());
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
            HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                    .build());
        return new RestTemplate(factory);
    }
}

But when I try to launch the application it gave me this Exception:

2020-11-20 13:39:44.831  WARN 5944 --- [           main]  ConfigServletWebServerApplicationContext : 

    Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource [hu/hazazs/blog/config/SslConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Factory method 'restTemplate' threw exception; nested exception is java.io.FileNotFoundException: ServletContext resource [/src/main/resources/keystore/theblog.p12] cannot be resolved to URL because it does not exist
    Exception in thread "task-2" java.lang.IllegalStateException: EntityManagerFactory is closed
        at org.hibernate.internal.SessionFactoryImpl.validateNotClosed(SessionFactoryImpl.java:509)
        at org.hibernate.internal.SessionFactoryImpl.getProperties(SessionFactoryImpl.java:503)
        at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.findDataSource(DataSourceInitializedPublisher.java:105)
        at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:97)
        at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50)
        at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
    2020-11-20 13:39:45.687 ERROR 5944 --- [           main]  o.springframework.boot.SpringApplication : Application run failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource [hu/hazazs/blog/config/SslConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Factory method 'restTemplate' threw exception; nested exception is java.io.FileNotFoundException: ServletContext resource [/src/main/resources/keystore/theblog.p12] cannot be resolved to URL because it does not exist
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:483)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
        at hu.hazazs.blog.BlogApplication.main(BlogApplication.java:15)
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Factory method 'restTemplate' threw exception; nested exception is java.io.FileNotFoundException: ServletContext resource [/src/main/resources/keystore/theblog.p12] cannot be resolved to URL because it does not exist
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650)
        ... 20 common frames omitted
    Caused by: java.io.FileNotFoundException: ServletContext resource [/src/main/resources/keystore/theblog.p12] cannot be resolved to URL because it does not exist
        at org.springframework.web.context.support.ServletContextResource.getURL(ServletContextResource.java:174)
        at hu.hazazs.blog.config.SslConfig.restTemplate(SslConfig.java:23)
        at hu.hazazs.blog.config.SslConfig$$EnhancerBySpringCGLIB$$66b79300.CGLIB$restTemplate$0(<generated>)
        at hu.hazazs.blog.config.SslConfig$$EnhancerBySpringCGLIB$$66b79300$$FastClassBySpringCGLIB$$59182ace.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
        at hu.hazazs.blog.config.SslConfig$$EnhancerBySpringCGLIB$$66b79300.restTemplate(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
        ... 21 common frames omitted

How can I do a proper reference to the .p12 file as trust-store?

tibotka
  • 144
  • 12

1 Answers1

0

I think you did the wrong config syntax following the tutorial.
The trust store will load from the classpath.

server:
ssl:
 
    trust-store: classpath:keystore/baeldung.p12
    trust-store-password: ********
   
Hai Mai
  • 370
  • 2
  • 6
  • with classpath: it gave me this error: `nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server` and `java.lang.IllegalArgumentException: the trustAnchors parameter must be non-empty` – tibotka Nov 20 '20 at 13:43
  • Following https://stackoverflow.com/questions/6784463/error-trustanchors-parameter-must-be-non-empty . Your app might not have permission to access the baeldng.p12. – Hai Mai Nov 20 '20 at 13:47