gpt4 book ai didi

java - 如何在 Heroku 下的 java cedar 堆栈中强制执行 HTTPS

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:30:44 28 4
gpt4 key购买 nike

我发现了很多关于在 heroku 下强制执行 HTTPS 的问题,但没有关于 java 的回应。

这是我找到的链接:

斯卡拉:http://www.andersen-gott.com/2012/03/using-unfiltered-and-https-on-heroku.html

导轨:Rails - How to Redirect from http://example.com to https://www.example.com

请注意,我使用的是 Spring MVC 3.1,所以我更喜欢基于 WebMvcConfigurerAdapter.addInterceptors(InterceptorRegistry registry) 的解决方案

最佳答案

这是一个将所有非 https 请求重定向到 https 的 Servlet 过滤器:

package com.jamesward;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpsEnforcer implements Filter {

private FilterConfig filterConfig;

public static final String X_FORWARDED_PROTO = "x-forwarded-proto";

@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;

if (request.getHeader(X_FORWARDED_PROTO) != null) {
if (request.getHeader(X_FORWARDED_PROTO).indexOf("https") != 0) {
response.sendRedirect("https://" + request.getServerName() + (request.getPathInfo() == null ? "" : request.getPathInfo()));
return;
}
}

filterChain.doFilter(request, response);
}

@Override
public void destroy() {
// nothing
}
}

我这样做是作为一个 Servlet 过滤器,因为我无法让 Spring 拦截器拦截静态 Assets (资源)请求。

完整来源:https://github.com/jamesward/springmvc-https-enforcer

关于java - 如何在 Heroku 下的 java cedar 堆栈中强制执行 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11892072/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com