首页 文章

Spring Boot HTTPS和重定向

提问于
浏览
0

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

我使用Spring Boot 1.2.4版本 .

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

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

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

谢谢,阿德里安

1 回答

  • 6

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

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                // ...
                .requiresChannel()
                    .anyRequest().requiresSecure();
        }
    }
    

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

    src/main/webapp/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>
    

    使用web.xml是必要的,因为无法以编程方式设置整个应用程序的安全性约束 . 你可以在How to programmatically setup a <security-constraint> in Servlets 3.x?找到一些相关的细节

相关问题