Spring Boot SSL [https] Example

In this spring boot example, learn to configure web application to run on SSL (HTTPS) with self-signed certificate. Also learn to create SSL cert, as well.

SSL Configuration for Impatients

Spring boot HTTPS Config

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

Redirect from HTTP to HTTPS

private Connector redirectConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(8080);
  connector.setSecure(false);
  connector.setRedirectPort(8443);
  return connector;
}

For detailed tutorial on how to setup whole thing, continue reading.

Table of Contents

Terminology
Create your own self signed SSL certificate
Create Spring-boot application and configure SSL
Redirect to HTTPS from HTTP

Terminology

Before moving further, let’s understand what specific terms such as SSL or TLS means.

SSL – stands for Secure Sockets Layer. It is the industry standard protocol for keeping an internet connection secure by safeguarding all sensitive data that is being sent between two systems, preventing hackers from reading and modifying any information transferred.

TLS – (Transport Layer Security) is an updated, more secure, version of SSL. It adds more features. Today, certificates provided by certificate authorities are based on TLS only. But regarding secured communication over network, the term SSL is still common as it is the old and just become popular among community.

HTTPS – (Hyper Text Transfer Protocol Secure) appears in the URL when a website is secured by an SSL certificate. It is the secured version of HTTP protocol.

Truststore and Keystore – Those are used to store SSL certificates in Java but there is little difference between them. truststore is used to store public certificates while keystore is used to store private certificates of client or server.

Create your own self signed SSL certificate

To get SSL digital certificate for our application we have two options –

  1. to create a self-signed certificate
  2. to obtain SSL certificate from certification authority(CA) we call it CA certificate.

For today’s demo purpose we will create self-signed certificate generated by java keytool command. We need to run the keytool -genkey command from command prompt.

Here is the exact command we will use –

keytool -genkey -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 -validity 700 -keypass changeit -storepass changeit -keystore ssl-server.jks

Let’s understand above command –

  • -genkey – is the keytool command to generate the certificate, actually keytool is a multipurpose and robust tool which has several options
  • -alias selfsigned_localhost_sslserver – indicates the alias of the certificate, which is used by SSL/TLS layer
  • -keyalg RSA -keysize 2048 -validity 700 – are self descriptive parameters indicating the crypto algorithm, keysize and certificate validity.
  • -keypass changeit -storepass changeit – are the passwords of our truststore and keystore
  • -keystore ssl-server.jks – is the actual keystore where the certificate and public/private key will be stored. Here we are using JKS fromat – Java Key Store, there are other formats as well for keystore.

Once we execute above command, it will ask for certain information and finally this will look like this.

keytool to generate the certificate

That’s all we need at this point regarding certification generation. This will generate the ssl-server.jks keystore file containing our self signed certificates in the directory from where keytool command has been executed.

To view what is inside this keystore we can again use the keytool -list command as bellow.

keytool -list -keystore ssl-server.jks

Output will be something like –

keytool -list option

Create Spring-boot project and configure SSL

Generate spring boot project

Create one spring boot project from SPRING INITIALIZR site with dependencies Web and Rest Repositories. After selecting the dependencies and giving the proper maven GAV coordinates, we will get download option in zipped format. Download the skeleton project, unzip and then import that in eclipse as maven project.

Spring boot project generation

Add REST endpoint

For testing purpose we will use one simple REST endpoint. To do that open the already generated spring boot application class annotated with @SpringBootApplication and add this code. This will expose one rest endpoint with relative URL /secured in the server.

@RestController
class SecuredServerController{
	
	@RequestMapping("/secured")
	public String secured(){
		System.out.println("Inside secured()");
		return "Hello user !!! : " + new Date();
	}
}

That’s all we need to add web contents in our application. You can add more like adding pages, images to create a fully functional web application.

Spring boot SSL Configuration

First we need to copy the generated keystore file (ssl-server.jks) into the resources folder and then open the application.properties and add the below entries.

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

That’s all we need to enable https. It’s pretty easy, right? Thanks to spring boot for making everything possible very easily.

Demo

Now it is time to do a final maven build by command mvn clean install and start the application by java -jar target\ssl-server-0.0.1-SNAPSHOT.jar command. This will start our secured application in localhost 8443 port and our end point url will be https://localhost:8443/secured.

Since our REST endpoint is exposed over GET, we can test it through browser only. Go to https://localhost:8443/secured and you will get some browser warning like certificate is not issued from trusted certificate authorities, add exception to that in browser and you will get response from HTTPS server just created by you.

Browser output

Redirect HTTP requests to HTTPS

This is an optional step in case you want to redirect your HTTP traffic to HTTPS, so that the full site becomes secured. To do that in spring boot, we need to add HTTP connector at 8080 port and then we need to set redirect port 8443. So that any request in 8080 through http, it would be automatically redirected to 8443 and https.

To do that you just need to add below configuration.

@Bean
public EmbeddedServletContainerFactory servletContainer() {
  TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
      @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;
}

private Connector redirectConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(8080);
  connector.setSecure(false);
  connector.setRedirectPort(8443);
  
  return connector;
}

Do a final maven build by command mvn clean install and start the application. Test http://localhost:8080/secured. It would be automatically redirected to HTTPS secured URL.

Summary

So today we learned, how we can enable HTTPS in spring boot application and also we have seen how we can redirect HTTP traffic to HTTPS. We also learned to create self signed SSL certificate.

Drop me your questions in comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
26 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode