Spring Boot使用redirect:/相对路径重定向时HTTPS跳HTTP问题
根因分析
Weblogic作为应用服务器在HTTPS部署场景下,客户端请求到Weblogic节点走的是HTTPS协议,但Weblogic内部转发请求到部署的Spring Boot应用时默认使用HTTP协议,Spring Boot原生逻辑会从HttpServletRequest的scheme属性读取协议值生成重定向地址,因此最终生成的重定向地址前缀为http://,触发浏览器混合源内容拦截规则。
解决方案
以下方案按推荐优先级排序:
- 方案1:开启Spring Boot代理头识别(无业务代码侵入,推荐)
Spring Boot原生支持识别反向代理转发的标准请求头,只需在应用配置文件中添加如下配置:
同时需要确认Weblogic域开启了代理头转发:登录Weblogic控制台 -> 进入对应域的配置页 -> 选择「Web应用程序」标签 -> 勾选「Web服务插件已启用」,保存配置后重启Weblogic域即可。开启后Weblogic会自动携带# application.properties 配置 server.forward-headers-strategy=nativeX-Forwarded-Proto等代理头,Spring Boot会自动读取头中的HTTPS协议生成重定向地址。 - 方案2:全局重定向规则强制HTTPS(适合无法修改服务器配置的场景)
自定义Spring MVC重定向视图逻辑,所有重定向地址自动替换协议为HTTPS,示例代码如下:import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Configuration public class RedirectConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.viewResolver((viewName, locale) -> { if (viewName.startsWith("redirect:")) { return new RedirectView(viewName.substring(9)) { @Override protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String targetUrl, boolean http10Compatible) throws IOException { // 强制替换HTTP协议为HTTPS if (targetUrl.startsWith("http://")) { targetUrl = targetUrl.replaceFirst("http://", "https://"); } super.sendRedirect(request, response, targetUrl, http10Compatible); } }; } return null; }); } } - 方案3:单接口手动构造重定向地址(适合少量接口临时适配)
直接在Controller层手动构造完整HTTPS重定向地址,无需修改全局配置:@GetMapping("/originPath") public void testRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectUrl = "https://" + request.getServerName() + "/targetRedirectPath"; response.sendRedirect(redirectUrl); }
内容的提问来源于stack exchange,提问作者Chiranjit Jasu
相关产品推荐
相关产品推荐

