我正在使用带有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();
}
}
}
对此的任何帮助都非常感谢。
答案 0 :(得分:54)
CSRF保护。要禁用它:
@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
...;
}
}
答案 1 :(得分:5)
您还可以使用http
对象的以下配置禁用仅对某些请求或方法的CSRF检查:
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;
}
});
你可以在这里看到更多: