Skip to main content

How to configure SSL certificate in spring boot?

Let us learn how to generate & configure the ssl certificates in spring boot applications.

how to configure ssl certificate in spring boot

Step 1. Getting the certificate 

We can purchase the SSL certificate from the following SSL providers  

  • Godaddy
  • DigiCert
  • GeoTrust
  • GlobalSign
  • Comodo SSL
  • RapidSSL
  • SSL.com

OR, for testing purposes, we can generate a self-signed certificate

Before getting started, let us know the format of the SSL certificates:

  • PKCS12: Public Key Cryptographic Standards is a password-protected format that can contain multiple certificates and keys; it's an industry-wide used format.
  • JKS: Java KeyStore is similar to PKCS12; it's a proprietary format and is limited to the Java environment.

To know more about how SSL works please go to this link.

We can use either keytool or OpenSSL tools to generate the certificates from the command line. Keytool is shipped with Java Runtime Environment, and OpenSSL can be downloaded from here.

For our demonstration, let's use keytool.

keytool -genkey -alias localhost -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore localhost.p12 -validity 365 -ext san=dns:localhost

This command will generate a key using the RSA cryptography algorithm. Arguments of the keytool program are stated below:

    • -genkey: generates a key
    • -alias localhost: defines the name of the key, here we have named 'localhost', which uniquely identifies your domain name
    • -storetype PKCS12: this defines the format of the key that is stored as 'PKCS12'
    • -keyalg RSA: used to specify the algorithm to be used is 'RSA'
    • -keysize 2048: used to define the size of the key as '2048' bit
    • -keystore localhost.p12: specifies the name of the file that stores the key is 'localhost.p12'
    • -validity 365: it is used to set the expiration date of the key will be '365' days from now
    • -ext san=dns:localhost: includes an X.509 extension for Subject Alternate Name (SAN)- a SAN is required so the certificated will be trusted by browsers on localhost

Note: The keytool program is available in JDK's bin directory, so you need to navigate to JDK_HOME\bin

generating ssl certificate command image

Step 2. Add the generated certificate file in your project

Copy and paste the generated key <localhost.p12>   into the resource folder of the project structure as shown below.  

how to configure ssl in spring boot project project structure

Step 3. Setting up the SSL configurations in application properties

Add the necessary SSL configuration to the application.properties file.

httpPort = 8080
server.port=8443
server.ssl.key-store: classpath:localhost.p12
server.ssl.key-store-password: abcd123
server.ssl.keyStoreType: pkcs12
server.ssl.keyAlias: localhost

Step 4. Add the connectors configurations

Add connectors configurations and port redirection from default port to secured port.

@Configuration
public class ConnectorConfig {

    @Value("${server.port}")
    int httpsPort;
    @Value("${httpPort}")
    int httpPort;
    /**
     * This method is used to get Servlet Container
     * @return ServletWebServerFactory
     */
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }
    /**
     * This method is used to get redirect Connector
     * @return Connector
     */
    private Connector redirectConnector() {

        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(httpPort);
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }
}

Step 5. Output screens

https port security risk exception

redirecting to https port in spring boot

Thanks for reading this article. I hope you understood well.

Popular posts from this blog

Custom Pagination with search and filters in Spring Boot

Every spring boot application is made to manage a large set of data. Also, we need to perform a search and filter the data according to need, And also we cannot load all data in one go on a single page so we need pagination too. In this article, we are going to demonstrate custom pagination with search and filter performed through ajax call. Goal: This demonstration is performed on a set of students' data. We have written a method to generate sample data.   Table of Contents 1. Initialize the project with the following dependencies 2. Set the application properties 3. Create the Student entity 4. Enum to denote the class of student 5. Create JPA repository of entity 6. Create the search & filter command object (CO) 7. Create a data transfer object (DTO) of the Entity for returning the response 8. Create a service for implementing the business login 9. Create a controller 10. Create a utility class for date conversions 11. Create the HTML Data Table design 12. ...

Request Mapping Annotation in Spring Boot

The @RequestMapping is a class level  (also called type level) and method level annotation, it is used to process HTTP requests with specified URL patterns. It is used in and along with both @Controller and @RestController . Table of Contents Request Mapping Annotation in Spring Boot 1. How @RequestMapping annotation it is used? 2. Optional Elements of @RequestMapping 2.1 name, value and path 2.2 headers, consumes and produces 3. Specialization of @RequestMapping 1. How @RequestMapping annotation it is used? @Controller @RequestMapping("/student") public class StudentController{ @RequestMapping("/dashboard") public String dashboard(){ return "dashboard"; } @RequestMapping("result") public String result(){ return "result"; } } We can see in above code sample "/student" , "/dashboard" and "result" passed with annotation are called request value/path present in the URL ...

Maven or Gradle - built tool selection in Spring Boot

  Spring Boot -Selection of built tool Gradle Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software, It is fully open source and similar to Maven and Ant. But Gradle has taken advantage of both Maven and Ant and also it has removed the disadvantages of Maven and Ant and created as a first-class built tool. It uses domain-specific language based on the programming language Groovy , differentiating it from Apache Maven, which uses XML for its project configuration. Gradle allows to create or customize built procedure and we can create an additional task with groovy scripts that can be executed before/after built. It also determines the order of tasks run by using a directed acyclic graph . Several developers created Gradle and first released in 2007, and in 2013, it was adopted by Google as the build system for Android projects. It was designed to support multi-project builds that are expected...

Application Properties And Environment Profiling In Spring Boot

Application Properties As we know Spring Boot configures almost all the configurations automatically, it also enables us to customize the configurations and properties according to our needs and environment. There are various methods which we can use to do the same. We can either write all properties in a textual file, do programmatically in our Java classes, or can set it while starting the application through CLI by passing command-line arguments. By default, Spring Initializr creates an application.properties file inside the project's class path. But we can also define it in the YAML file. Know the differences between the .properties file and .yml file The properties that we are talking about are database credentials and URL, server port, logging file path, catch control variables, can write any custom string constants, etc. Table of Contents Application Properties  Method 1: Using application.properties  Method 2: Using application.yml file  Method 3...