Search code examples
spring-bootdockerssl-certificatespring-boot-maven-pluginspring-boot-security

Adding SSL certificate to cacerts file inside Spring-Boot container


I have a Spring Boot application that I use as docker container on my server. To generate docker image I run the maven plugin using the buildpack.

mvn spring-boot:build-image -Dspring-boot.build-image.imageName="csm-security"

To start the container I use a docker-compose.yml file.

version: '3' 
networks:
  wso2_bridge: 
services:
  csm-security:
    image: csm-security:$IMAGE_VERSION_CSM_SECURITY
    container_name: csm-security
    ports:
      - "8877:8877"
    networks:
      - wso2_bridge

My problem is that I added authorization to this application and now I need to import a certificate inside this docker to validate the token.

Is there any elegant way to add SSL certificates to Spring-Boot images or docker containers to be used when I run the application?


Solution

  • There are a couple of options, depending on what you want to do with the certificate in the container.

    If you want the certificate files to be accessible by code in your app, then you can put them in src/main/resources so they will be picked up automatically and added to the jar file, or put them somewhere else and configure the Maven resources plugin to copy them to the jar.

    The second option is to have buidpacks add them to the JDK trust store when the image is built, as @anthony-dahanne mentioned in a comment above. To do that with the Spring Boot Maven plugin you can follow these steps (copied from a similar answer to another post, but without the native image aspect from the other post).

    First create a bindings directory in the root of your project structure (at the same level as the project src directory) and copy the custom certificate to that directory (where my-custom-certificate.crt is a CA certificate in PEM format):

    $ mkdir -p bindings/certificates
    $ echo "ca-certificates" > bindings/certificates/type
    $ cp /some/path/to/my-custom-certificate.crt bindings/certificates/my-custom-certificate.crt
    $ tree bindings
    bindings
    ├── certificates
    │   ├── my-custom-certificate.crt
    │   └── type
    

    Then configure the Spring Boot Maven plugin to provide the binding to the Paketo CNB builder when the image is built:

      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <image>
            <bindings>
              <binding>${basedir}/bindings/certificates:/platform/bindings/ca-certificates</binding>
            </bindings>
          </image>
        </configuration>
      </plugin>