В Spring -Security с Java Config, почему httpBasic POST хочет токен csrf?
Я использую Spring -Security 3.2.0.RC2 с конфигурацией Java.
Я создал простой HttpSecurity config, который запрашивает базовое auth on/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();
}
}
}
Любая помощь по этому поводу очень ценится.
Ответы
Ответ 1
CSRF защита включена по умолчанию с конфигурацией Java. Чтобы отключить его:
@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
...;
}
}
Ответ 2
Вы также можете отключить проверку 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/