【问题标题】:Trying to set up proper HTTPS with Spring Boot 4尝试使用 Spring Boot 4 设置正确的 HTTPS
【发布时间】:2017-09-26 17:17:24
【问题描述】:

我有一个 Spring Boot 应用程序,它在没有 HTTPS 的情况下运行得非常好。现在,我获得了在 prod 环境中使用的 SSL 证书,我现在想将所有端点默认设置为 HTTPS。

我一直在使用 Spring Security 来配置我的页面的访问权限,这就是我所拥有的:

protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(
                        "/images/**",
                        "/css/**",
                        "/js/**",
                        ....bunch of endpoints....
                        "/").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .failureUrl("/login")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID", "remember-me")
                .logoutSuccessUrl("/")
                .permitAll()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/error");

我读到你可以将它添加到我上面的配置中以强制所有请求使用 HTTPS,但我想确定它应该去哪里,这样我就不会中断生产:

.requiresChannel().anyRequest().requiresSecure();

我正在通过 AWS Elastic Beanstalk 运行我的应用程序,并且 SSL 证书已经 已成功在 AWS 上正确安装(准备就绪)。 澄清一下,SSL/HTTPS 在负载平衡处终止,而不是在 EC2 实例处终止,所以我猜这可能会更改 Spring Boot 中的配置?

另外,如果我也可以在我的机器上使用 Spring 本地测试 https,那就太好了,但我不确定如何继续。很多在线示例看起来都非常复杂。

大家对此有何建议?谢谢

【问题讨论】:

    标签: spring ssl spring-boot spring-security https


    【解决方案1】:

    是的,要强制使用 HTTPS,您需要添加以下代码行

    http.requiresChannel().anyRequest().requiresSecure();
    

    要在本地进行测试,您需要在本地安装证书并需要以下配置

    在 Spring Boot 中启用 HTTPS:

    在您的 application.properties 中定义以下属性:

    # Define a custom port instead of the default 8080
    server.port = 8089
    # Tell Spring Security to require requests over HTTPS
    security.require-ssl=true
    # The keystore containing the certificate keys
    server.ssl.key-store=keystore.jks
    # The password used to generate the keys
    server.ssl.key-store-password=password
    # The alias mapped to the certificate
    server.ssl.keyAlias=tomcat
    

    启用 HSTS

    HTTP 严格传输安全 (HSTS) 是一种网络安全策略机制,有助于保护网站免受协议降级攻击和 cookie 劫持。它允许 Web 服务器声明 Web 浏览器(或其他符合要求的用户代理)只能使用安全的 HTTPS 连接[1] 与它进行交互,而不是通过不安全的 HTTP 协议。

    Strict-Transport-Security: max-age=31536000; includeSubDomains
    

    【讨论】:

    • 很好,谢谢,即使您尝试通过 HTTP 访问服务器,这是否会强制 Spring 自动重定向到 HTTPS?
    • 太棒了,谢谢,我会试试这个,让你知道结果如何
    • 嗨 Vaquar,就我而言,SSL/HTTPS 将在 AWS 负载均衡器级别终止,而不是实例。所以这可能意味着我不应该在我的 Spring Boot 中乱来,对吧?但是,我确实想将所有 HTTP 流量重定向到我的 HTTPS,并且在我的 Amazon 负载均衡器上,HTTP 和 HTTPS 都映射到同一个实例端口 80,因为 nginx 监听它。我是否需要以某种方式修改 nginx 以使重定向工作?
    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 2015-07-20
    • 2017-03-16
    • 2020-08-31
    • 2018-01-27
    • 1970-01-01
    • 2011-07-01
    • 2018-06-24
    相关资源
    最近更新 更多