java - Spring Boot HTTPS 和重定向

标签 java spring tomcat spring-boot security-constraint

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

我使用的是 Spring Boot 1.2.4 版本。

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

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

请问我如何使用 spring boot 实现相同的效果?

谢谢, 阿德里安

最佳答案

如果您使用的是 Spring Security,您可以通过将 security.require_ssl=true 添加到您的 application.properties 中来做到这一点,如 the Spring Boot reference 中所述.如果你自定义 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? 中找到一些详细信息

关于java - Spring Boot HTTPS 和重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226279/

相关文章:

java - 将 Java 8 GC 日志重定向到 stderr

java - 避免对 Spring 配置类进行类路径扫描

java - 如何通过 "Global default typing"在 Jackson 中启用 "jackson2ObjectMapperBuilder"

linux - 使用 service tomcat8 start 服务 tomcat8 启动失败

tomcat - 获取 Apache Tomcat 的端口号

java - Eclipse 中的 Maven 选项消失了

java - XmlHttp 内容序列化程序按字母顺序对字段进行排序

java - 如何通过 Spring 框架从数据库加载应用程序属性 (v4.0.3)

apache - Tomcat 的 URL 重写不起作用

java - 我如何告诉程序向对象添加新字段?