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()
.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With