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

2

10

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

Mote answered 9/7, 2014 at 9:51 Comment(0)
M
14

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();
    }
}
Mote answered 9/7, 2014 at 9:51 Comment(2)
Using the above I get "ERR_TOO_MANY_REDIRECTS" error, did you face a similar issue?Goodrich
follow this guide: baeldung.com/spring-channel-security-httpsJimmyjimsonweed
F
0
http.requiresChannel(channelRequestMatcherRegistry -> channelRequestMatcherRegistry.anyRequest().requiresSecure());
Fetiparous answered 8/8 at 7:14 Comment(1)
Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Carpentaria

© 2022 - 2024 — McMap. All rights reserved.