Spring Boot HTTPS和重定向

Adr*_*luk 0 java spring tomcat security-constraint spring-boot

我使用Spring STS和Pivotal 3.1服务器(端口8080和8443)我在盒子上还有一个单独的tomcat 7实例,它运行在80和443上.

我使用Spring Boot 1.2.4版本.

我希望应用程序自动将所有请求重定向到https - 我没有使用嵌入式tomcat实例.

以前使用spring我在web.xml中有标签,它工作得很好.

我怎么能用弹簧靴来实现同样的目的呢?

谢谢,阿德里安

Rob*_*nch 6

如果您使用的是Spring Security,则可以通过添加Spring Boot引用中security.require_ssl=true提到的application.properties 来完成此操作.如果您自定义Spring Security配置,那么您将需要具有以下内容:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .requiresChannel()
                .anyRequest().requiresSecure();
    }
}
Run Code Online (Sandbox Code Playgroud)

由于您没有使用Spring Security并且您正在使用war文件,因此最简单的方法是创建一个包含以下内容的web.xml:

的src /主/ web应用/ WEB-INF/web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee                       http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>all</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
</web-app>
Run Code Online (Sandbox Code Playgroud)

使用web.xml是必要的,因为无法以编程方式设置整个应用程序的安全性约束.您可以在Servlets 3.x如何以编程方式设置<security-constraint>中找到有关详细信息