How to redirect HTTP requests to HTTPS using Sprin

2019-02-06 18:48发布

问题:

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().

回答1:

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