选择性使用Spring Security的CSRFfilter
免责声明:我的问题有点类似于这个问题和这个问题 ,但我已经尝试了在这些主题中提出的所有答案,并且已经花了几天时间来解决这个问题。
我在现有的应用程序(JSP,Servlet)中引入了Spring Security 3.2.6,我正在使用Java配置。 我的应用程序将被浏览器和非浏览器客户端使用。 我希望所有对URL的浏览器请求(即/webpages/webVersion/
和/webpages/webVersion2/
)都启用CSRF,并且所有其他请求都禁用CSRF。 非浏览器客户端从不访问上述两个URL,而浏览器应用程序也可以访问CSRF禁用的URL。
我尝试了各种选择:
-
仅在前面提到的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。
-
尝试使用
CSRFProtectionMatcher
:.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);
CSRF仅针对预期的URL启用,但是甚至需要在匹配函数内检查
/resources/**
和/webpages/**
URL。 考虑到它将适用于所有请求似乎有点多。 -
尝试使用另一个版本的
configure
方法:@Override public void configure(WebSecurity web) throws Exception { web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?"); }
我不确定我是否正确地做了但这并没有产生我想要的结果。
以上哪种方法是正确的(Spring Security)做我想要的方式? 如何从Spring Security配置中实现所需的行为?
事实certificate,他们的配置有些错误,最后我使用方法3实现了目标。我使用了以下版本的configure函数以及通常的configure(HttpSecurity http)
函数。
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?"); }