Spring Boot SSL Example | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

SSL Configuration

Spring boot HTTPS Config

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=codefactory
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;
}

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.

To create a self-signed certificate using Java, we use keytool command. We need to run the keytool -genkey command from command prompt.

Run below command

keytool -genkey -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 -validity 700 -keypass codefactory -storepass changeit -keystore ssl-server.jks
  • -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 codefactory -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.

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.

Use SSL certificate in Spring Boot project

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.codeFactory</groupId>
	<artifactId>spring-boot-ssl</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-ssl</name>
	<description>Demo project for Spring Boot SSL</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.properties

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

SpringBootSslApplication.java

package com.codeFactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author code.factory
 *
 */
@SpringBootApplication
public class SpringBootSslApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSslApplication.class, args);
	}

}

SslController.java

package com.codeFactory.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author code.factory
 *
 */
@RestController
public class SslController {

	@GetMapping("/hello")
	public String hello() {
		return "Hello Code Factory...";
	}
}

Hit URL : https://localhost:8443/hello

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.

package com.codeFactory;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

/**
 * @author code.factory
 *
 */
@SpringBootApplication
public class SpringBootSslApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSslApplication.class, args);
	}

	@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;
	}

	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;
	}
}

Hit URL : localhost:8080/hello

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s