Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 510
Samuli Pahaoja Avatar asked Jul 09 '14 09:07

Samuli Pahaoja


People also ask

How do I change from HTTP to HTTPS in spring?

Redirect HTTP requests to HTTPS 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.


1 Answers

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();
    }
}
like image 128
Samuli Pahaoja Avatar answered Sep 23 '22 23:09

Samuli Pahaoja