我正在使用带有Java配置的Spring-Security 3.2.0.RC2.我设置了一个简单的HttpSecurity配置,要求/ v1/**上的基本身份验证.GET请求工作但POST请求失败:
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
我的安全配置如下所示:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Resource private MyUserDetailsService userDetailsService; @Autowired //public void configureGlobal(AuthenticationManagerBuilder auth) public void configure(AuthenticationManagerBuilder auth) throws Exception { StandardPasswordEncoder encoder = new StandardPasswordEncoder(); auth.userDetailsService(userDetailsService).passwordEncoder(encoder); } @Configuration @Order(1) public static class RestSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/v1/**").authorizeRequests() .antMatchers("/v1/**").authenticated() .and().httpBasic(); } } }
对此的任何帮助都非常感谢.
默认情况下,使用Java配置启用CSRF保护.要禁用它:
@Configuration public class RestSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() ...; } }
您还可以仅对某些请求或方法禁用CSRF检查,使用http
对象的以下配置:
http .csrf().requireCsrfProtectionMatcher(new RequestMatcher() { private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$"); private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null); @Override public boolean matches(HttpServletRequest request) { // CSRF disabled on allowedMethod if(allowedMethods.matcher(request.getMethod()).matches()) return false; // CSRF disabled on api calls if(apiMatcher.matches(request)) return false; // CSRF enables for other requests return true; } });
你可以在这里看到更多:
http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/