【问题标题】:heroku : spring boot acces to endpoints with https onlyheroku:spring boot 仅使用 https 访问端点
【发布时间】:2016-07-18 10:55:54
【问题描述】:

我在 heroku 上部署了一个 Spring Boot java 应用程序。我想确保我的注册端点只能通过 https 访问。到目前为止,我知道,heroku 使用负载均衡器,它将每个 https 连接重定向到带有特殊标头(X-forwarded-porto)的 http。 我正在使用

compile("org.springframework.boot:spring-boot-starter-security")

用于加密工具(散列密码)。我已将“security.basic.enable”属性设置为 false(实际上不知道在这种情况下是否重要。)。

已尝试设置这些设置:

tomcat:
  remote_ip_header: x-forwarded-for
  protocol_header: x-forwarded-proto

在我的 application.yml 中

问题是,我如何才能真正强制端点只能通过 https 链接使用?对于 http 它可以返回 404 或其他东西。我正在使用 gradle,它很难找到任何使用它的参考。尝试了一些在谷歌中找到的东西,但它没有用(或者我不知道如何正确实现它们......)。我仍然可以使用邮递员通过 http 访问我的端点。 现在它看起来像这样:

@Controller
@RequestMapping("/users")
public class AccountController {
    @Autowired
    private AccountRepository accountDao;

    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
    public ResponseEntity<Resource<Account>> createAccount(@RequestBody @Valid Account account) { ... }

【问题讨论】:

    标签: java spring heroku


    【解决方案1】:

    其实我在这个 repo https://github.com/fenrirx22/springmvc-https-enforcer 中找到了一个解决方案(finally)。

    创建了 2 个类:

    @Configuration
    public class ApiConfig {
        @Bean
        public Filter httpsEnforcerFilter(){
            return new HttpsEnforcer();
        }
    }
    

    和:

    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());
                    return;
                }
            }
    
            filterChain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
            // nothing
        }
    }
    

    像魅力一样工作。

    【讨论】:

    • 我会对该答案进行更改。在响应重定向字符串中将 request.getPathInfo() 更改为 request.getPathInfo() == null ? "" : request.getPathInfo() 来正确处理没有路径信息的情况。
    • 嗨!你的 Procfile 看起来怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2015-07-22
    • 2016-06-01
    • 2022-10-15
    • 2018-03-26
    • 2021-10-14
    • 2020-01-10
    相关资源
    最近更新 更多