【问题标题】:How to handle security.enable-csrf in Spring Boot 2?如何在 Spring Boot 2 中处理 security.enable-csrf?
【发布时间】:2019-03-01 01:51:20
【问题描述】:

我正在将应用程序从 Spring Boot 1.5 迁移到 2.0.5。 我在 1.5 版本中有一个属性设置为 security.enable-csrf=true,这在 Spring Boot 2.0 版本中不可用。

我阅读了文档,据说在 Spring Boot 2.0 中:

在 Java 配置中默认启用 CSRF 保护。

所以默认情况下它是启用的,但是还创建了一个扩展 WebSecurityConfigurerAdapter 的类,这意味着 Spring Boot 默认安全配置已关闭。这是否也意味着security.enable-csrf 现在被禁用了?

如果是,我该如何启用它,就像我在 1.5 版本的应用程序中一样。

我没有得到任何文件明确确认如何在 Spring Boot 2.0 中处理 security.enable-csrf 属性以及声明 WebSecurityConfigurerAdapter。

有人知道吗?此外,我错过的任何文档链接都会有很大帮助。

【问题讨论】:

  • 如果你只扩展 WebSecurityConfigurerAdapter 而不禁用默认值,它仍然是打开的。只有在没有找到其他 WebSecurityConfigurerAdapter 时,WebSecurityConfigurerAdapter 的 Spring Boot 可用扩展才会启动。 Spring Boot 默认类只使用 Spring Security 默认值(它是一个空实现)。

标签: spring-boot spring-security


【解决方案1】:

WebSecurityConfigurerAdapter是一个抽象类,当你创建一个扩展WebSecurityConfigurerAdapter的类时,你会覆盖void configure(HttpSecurity http)方法。

你可以在这个方法中禁用csrf,就像那样;

http.csrf().disable();

您可以在csrf() 方法(在HttpSecurity 类中)之上阅读此评论。

添加 CSRF 支持。使用时默认激活 WebSecurityConfigurerAdapter 的默认构造函数。你可以禁用它....”

这条评论说,当你扩展这个类时,WebSecurityConfigurerAdapter 的默认构造函数工作并且 csrf 被激活。

【讨论】:

    【解决方案2】:

    为了向后兼容您应用程序中已设置的属性security.enable-csrf=true,您可以使用以下代码:

    @EnableWebSecurity
    public class WebSecurityConfig extends
    WebSecurityConfigurerAdapter {
    
        @Value("${security.enable-csrf}")
        private boolean csrfEnabled;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            if (!csrfEnabled) {
                http.csrf().disable();
            }
        }
    }
    

    正如您可能猜到的那样,魔法来自http.csrf().disable(); 在上面的代码中,您可以控制启用/禁用它 您在 application.properties 文件中设置的属性。


    更多信息:

    更多细节也可以参考spring文档:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-25
      • 2019-07-31
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2017-12-17
      相关资源
      最近更新 更多