如何使用 Spring Boot 自动重定向到 https [英] How to redirect automatically to https with Spring Boot

查看:47
本文介绍了如何使用 Spring Boot 自动重定向到 https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松配置嵌入式 tomcat 服务器以将所有 http 流量重定向到 https?我在弹性负载均衡器后面的 ec2 实例上运行 Spring Boot.我已将 ELB 配置为为我处理 ssl(这很棒),并将 X-FORWARDED-PROTO 标头设置为https".我想检测何时未设置,并重定向用户以强制他们使用 https(如果尚未设置).

How I can easily configure the embedded tomcat server to redirect all http traffic to https? I have Spring Boot running on an ec2 instance that is behind an elastic load balancer. I have configured the ELB to handle ssl for me (which is awesome) and it sets the X-FORWARDED-PROTO header to "https". I want to detect when that isn't set, and redirect the user to force them to use https if they aren't already.

到目前为止,我已经尝试将以下内容添加到我的 application.properties 文件中,但没有成功:

So far, I have tried adding the following to my application.properties file with no luck:

server.tomcat.protocol-header=x-forwarded-proto
security.require-ssl=true

推荐答案

我的回答有点晚了,但我最近遇到了这个问题,想发布一个对我有用的解决方案.

My answer is a little late but I just recently had this problem and want to post a solution which worked for me.

最初,我认为将 tomcat 设置为使用 X-Forwarded 标头就足够了,但是来自 Tomcat 的 RemoteIPValve(通常应该处理这种情况)对我不起作用.

Originally, I thought that setting tomcat up to use the X-Forwarded headers would suffice but the RemoteIPValve from Tomcat, which should normally handle this case, didnt work for me.

我的解决方案是添加一个 EmbeddedServletContainerCustomizer 并添加一个 ConnectorCustomizer:(注意我这里使用的是Tomcat 8)

My solution was to add an EmbeddedServletContainerCustomizer and add a ConnectorCustomizer: (note that I am using Tomcat 8 here)

@Component
public class TomcatContainerCustomizer implements EmbeddedServletContainerCustomizer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TomcatContainerCustomizer.class);

    @Override
    public void customize(final ConfigurableEmbeddedServletContainer container) {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            final TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
            tomcat.addConnectorCustomizers(connector -> { 
                connector.setScheme("https");
                connector.setProxyPort(443);
            });
            LOGGER.info("Enabled secure scheme (https).");
        } else {
            LOGGER.warn("Could not change protocol scheme because Tomcat is not used as servlet container.");
        }
    }
}

重要的是,您不仅将 Scheme 设置为 https,还设置了 ProxyPort,否则所有来自 Spring Boot 的内部重定向都将路由到端口 80.

The important thing is that you not only set the Scheme to https but also the ProxyPort without which all internal redirects from Spring Boot were routed to port 80.

这篇关于如何使用 Spring Boot 自动重定向到 https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆