javaspringsecurityspring-securityspring-java-config

How to redirect HTTP requests to HTTPS using Spring Security Java configuration?


I have a Spring Security version 3.2.3 application that listens to both HTTP and HTTPS. I want any request to the HTTP port to be redirected to HTTPS. How do I configure that using Java only?

Spring Security javadoc for HttpSecurity proposes the following solution (trimmed to the essential):

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http.channelSecurity().anyRequest().requiresSecure();
    }
}

However that doesn't work because HttpSecurity doesn't have method channelSecurity().


Solution

  • Replacing channelSecurity() with requiresChannel() in the code in the question appears to give the desired behaviour. The working code then looks as following:

    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) {
            http.requiresChannel().anyRequest().requiresSecure();
        }
    }