【发布时间】:2015-08-10 11:24:41
【问题描述】:
免责声明:我的问题有点类似于this question 和this question,但我已经尝试了这些帖子中建议的所有答案,并且已经花了几天的时间来解决这个问题。
我在我现有的应用程序(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 配置中实现所需的行为?
【问题讨论】:
标签: java spring spring-security csrf-protection