【问题标题】:How to enable/disable CSRF in Spring at runtime?如何在运行时在 Spring 中启用/禁用 CSRF?
【发布时间】:2020-08-18 17:29:05
【问题描述】:

我有以下具有 CSRF if/else 条件的课程。我从属性文件中读取了这个标志,我可以使用 /refresh 端点更改标志值。 :

    @Order(-1)
    @EnableWebSecurity
    public class SomeConfigClass extends WebSecurityConfigurerAdapter {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                 String csrfFlag = somePropertyFile.getCsrfFlag();
                 if(isCsrfEnable){
                      http.csrf()....some other code
                 }else {
                      http.csrf().disable();
                 }
            }
    }

问题: 所以当我调试代码时,我知道这个类只在 Spring 容器启动时调用一次。之后 if 将不会被调用。因此,即使在将 CSRF 标志更改为 false 之后,打算关闭 CSRF 标志,也不会工作,并且 CSRF 检查将在那里。

为避免这种情况,我需要重新启动/重新暂存应用程序,以便容器从属性文件中获取新配置,这可能会导致应用程序停机。 谁能更好地解决这个问题?

目标: CSRF 禁用/启用标志应该被外部化。 可以切换标志并启用/禁用 CSRF,而无需重新启动/重新部署应用程序。

【问题讨论】:

    标签: java spring spring-boot csrf


    【解决方案1】:

    您需要使用 csrf 保护匹配器来实现相同的功能。

    你需要编写 CSRFProtectionMatcher。

     http.csrf().requireCsrfProtectionMatcher(new CustomCsrfProtectionMatcher())
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    

    CustomCsrfProtectionMatcher.java

    public class CustomCsrfProtectionMatcher implements RequestMatcher {
    
    
        @Override
        public boolean matches(HttpServletRequest request) {
          //based on the logic..
          //You can store flag in DB or properties or XML File
          //Please note that for every request this flag will be checked.You can choose a 
          //better way to implement this
          return true/false;
        }
    }
    

    我个人建议保留在 app.properties 中,而不是根据请求检查它。

    【讨论】:

    • 目前我只这样做。我已经编写了自定义匹配器,它检查每个请求,并从属性文件中获取 CSRF 的标志,该标志将是真或假。
    • 但是您的配置方法仅在应用程序启动时执行。但是“CustomCsrfProtectionMatcher”是每个请求执行的请求匹配器..尝试实现代码并调试它
    • 正如我在第一条评论中所说,我现在正在使用该解决方案。但我想要解决我提到的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 2019-11-07
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2018-08-09
    • 2014-05-23
    • 1970-01-01
    相关资源
    最近更新 更多