Spring Boot HTTPS and redirect

4.1k Views Asked by At

I am using Spring STS with Pivotal 3.1 server (ports 8080 and 8443) I have also a separate tomcat 7 instance on the box which runs on 80 and 443.

I use Spring Boot 1.2.4 release.

I would like the application to automatically redirect all requests to https - I am not using embedded tomcat instance.

Previously using spring I had tag in web.xml and it was working just fine.

How can I achieve the same using spring boot please ?

Thanks, Adrian

1

There are 1 best solutions below

2
On BEST ANSWER

If you were using Spring Security you could do this by adding security.require_ssl=true to your application.properties as mentioned in the Spring Boot reference. If you customize the Spring Security configuration, then you will want to have something like this:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .requiresChannel()
                .anyRequest().requiresSecure();
    }
}

Since you aren't using Spring Security and you are using a war file the easiest way is to create a web.xml with the following in it:

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee                       http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>all</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
</web-app>

Using a web.xml is necessary because there is no way to setup a security constraint of the entire application programatically. You can find some details on that in How to programmatically setup a <security-constraint> in Servlets 3.x?