Enable SSL in Spring Boot

Hi,

In this article I'll show you how you can enble SSL using self signed certificate.

Remember this will show you a warning if you access app from the browser saying your connection is not private. Like this,



Using self signed certificate is useful in development environment but we'll see in future article how we can enable it in production environment.

1. Generate Keystore


keytool -genkey -keyalg RSA -alias keyname -keystore keystore.jks -storepass keypass -validity 360 -keysize 2048

Here we're creating a keystore named 'keystore.jks' with a password 'keypass' and an alias 'keyname'. Well not yet, after executing this command your terminal will prompt to get some informations like this



A keystore (keystore.jks) will be generated in your current directory. No you need to use this keystore to enable ssl.

 

2. Enable SSL


First copy kaystore.jks file in your project root directory or any directory you want. Write some configuration properties in your application.properties file.
server.ssl.key-store=keystore.jks
server.ssl.key-store-password=keypass
server.ssl.key-store-type=JKS
server.ssl.key-alias=keyname
server.ssl.key-password=keypass

Holy crap! you need to do nothing but adding these lines above and your application will serve your requests over https.

3. Redirect HTTP to HTTPS (optional)


Well, you may want to redirect all of your requests to https now, since http probably doesn't work in this moment. No problem, add two beans in your configuration class (annotated with @Configuration)
// Redirect http to https config beans
@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(initiateHttpConnector());
return tomcat;
}

private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8081);

return connector;
}

Now all of your request over http in port 8081 will be transferred to port 8080 over https. For example, http://localhost:8081 to https://localhost:8080

Comments

Popular posts from this blog

Deploy Spring Boot app in digitalocean cloud (or any cloud as long asyou have ssh access)

Upload large files : Spring Boot

User activity logging: Spring