如何使用 Spring Security Java 配置将 HTTP 请求重定向到 HTTPS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24650450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:46:23  来源:igfitidea点击:

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

javaspringsecurityspring-securityspring-java-config

提问by Samuli Pahaoja

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?

我有一个侦听 HTTP 和 HTTPS 的 Spring Security 3.2.3 版应用程序。我希望对 HTTP 端口的任何请求都重定向到 HTTPS。如何仅使用 Java 进行配置?

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

Spring Security javadoc forHttpSecurity提出了以下解决方案(修剪到本质):

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

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

但是这不起作用,因为HttpSecurity没有 method channelSecurity()

采纳答案by Samuli Pahaoja

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

更换channelSecurity()requiresChannel()在问题的代码似乎得到期望的行为。工作代码如下所示:

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