有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring引导HTTPS和重定向

我正在使用SpringSTS和Pivotal 3.1服务器(端口8080和8443) 我在运行的box上还有一个单独的Tomcat7实例 在80和443

我使用Spring Boot 1.2.4版本

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

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

我如何使用spring boot实现同样的效果

谢谢, 阿德里安


共 (1) 个答案

  1. # 1 楼答案

    如果您使用的是Spring安全性,那么可以通过向应用程序中添加security.require_ssl=true来实现这一点。如the Spring Boot reference中所述的属性。如果您自定义了Spring安全配置,那么您将需要如下内容:

    @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>
    

    使用网络。xml是必要的,因为无法通过编程方式设置整个应用程序的安全约束。你可以在How to programmatically setup a <security-constraint> in Servlets 3.x?中找到一些关于这方面的详细信息