【问题标题】:Selective usage of Spring Security's CSRF filterSpring Security 的 CSRF 过滤器的选择性使用
【发布时间】:2015-08-10 11:24:41
【问题描述】:

免责声明:我的问题有点类似于this questionthis question,但我已经尝试了这些帖子中建议的所有答案,并且已经花了几天的时间来解决这个问题。

我在我现有的应用程序(JSP,仅限 Servlet)中引入 Spring Security 3.2.6,并且我正在使用 Java 配置。我的应用程序将被浏览器和非浏览器客户端使用。我希望所有对 URL 的浏览器请求(即/webpages/webVersion//webpages/webVersion2/)都启用 CSRF,并且所有其他请求都禁用 CSRF。非浏览器客户端永远不会访问以上两个 URL,而浏览器应用程序也可能访问禁用 CSRF 的 URL。

我尝试了多种选择:

  1. 仅在上述 URL 上启用 Spring Security:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/","/resources/****").permitAll()
            .antMatchers("/webpages/webVersion/****", "/webpages/webVersion2/****").authenticated()
            .antMatchers("/webpages/****").permitAll()
            .anyRequest().anonymous()
            .and()
            .formLogin().loginPage("/webpages/webVersion/login/newLogin.jsp").failureUrl("/webpages/webVersion/login/newLogin.jsp?error=true").loginProcessingUrl("/j_spring_security_check")
            .usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/webpages/webVersion/login/loginSuccess.jsp", true).permitAll()
            .and()
            .logout().logoutUrl("/webpages/webVersion/logout.jsp").permitAll()
            .and().exceptionHandling().accessDeniedPage("/webpages/webVersion/404-error-page.jsp")
            .and()
            .csrf();
    } 
    

    这不起作用,因为我观察到所有 URL 都启用了 CSRF。

  2. 尝试使用CSRFProtectionMatcher

    .csrf().requireCsrfProtectionMatcher(csrfRequestMatcher); 
    

    CSRF 仅对预期 URL 启用,但即使是 /resources/**/webpages/** URL 也需要在匹配函数中进行检查。考虑到它将适用于所有请求,似乎有点多。

  3. 尝试使用另一个版本的 configure 方法:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?");
    }
    

    我不确定我是否做得正确,但这并没有产生我想要的结果。


以上哪种方法是正确的(Spring Security)方法来做我想做的事?如何从我的 Spring Security 配置中实现所需的行为?

【问题讨论】:

    标签: java spring spring-security csrf-protection


    【解决方案1】:

    原来是我的配置出现了一些错误,最后我使用方法 3 实现了目标。我使用了以下版本的配置功能以及通常的 configure(HttpSecurity http) 功能..

    @Override
    public void configure(WebSecurity web) throws Exception {
      web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?");
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2012-09-28
      • 2015-05-22
      • 2016-10-26
      • 2021-05-06
      • 2013-04-13
      • 2016-09-01
      • 1970-01-01
      相关资源
      最近更新 更多