Я искал этот вопрос в stackoverflow, но нашел вопрос, где csrf включен и игнорируется для определенного пути.
Я хочу сделать прямо противоположное. У меня много конечных точек, и я хочу отключить csrf для всего пути и включить только несколько путей.
Я использую весеннюю загрузку и имею класс WebSecurityConfig.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(listOfEndPoints).permitAll()
.anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
}
Итак, я хочу отключить csrf для всех возможных конечных точек и перезаписать в другой функции, где csrf защищена только небольшая часть пути (два или три пути).




Что ж, я думаю, вы можете разделить свою конфигурацию безопасности на несколько внутренних статических классов для достижения этой цели:
/**
* @author slemoine
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Configuration
@Order(1)
public static class CsrfDisabledSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String MATCHER = "/nocsrf/**";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher(MATCHER).authorizeRequests()
.anyRequest()
.authenticated().and()
.csrf().disable();
}
}
@Configuration
@Order(2)
public static class WithCsrfSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String MATCHER = "/withcsrf/**";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher(MATCHER).authorizeRequests()
.anyRequest().authenticated();
}
}
@Configuration
@Order(3)
public static class VariousUriWithCsrfDisabledSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/path1/**")
.antMatcher("/path2/**")
.authorizeRequests()
.anyRequest().authenticated()
.and().csrf().disable();
}
}
}
Первые две статические внутренние конфигурации показывают, как установить или отключить csrf для общего корневого пути. Третий отключает csrf на некоторых определенных путях.
Или, если вам нужна более прямая реализация, ответившая на ваш вопрос:
/**
* @author slemoine
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Configuration
@Order(1)
public static class VariousUriWithCsrfEnabledSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/path1/**")
.antMatcher("/path2/**")
.authorizeRequests()
.anyRequest().authenticated();
}
}
@Configuration
@Order(2)
public static class CsrfDisabledSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated().and()
.csrf().disable();
}
}
}
Нет, первый SecurityFilterChain имеет приоритет из-за @Order (1), если URL-адрес / path1 / ** или / path2 / **.
Я дважды проверил его, попытаюсь поставить точку останова на класс CsrfFilter и DefaultSecurityFilterChain (метод сопоставления), он должен быть в порядке в соответствии с вашими потребностями.
Разве второй подход (CsrfDisabledSecurityConfig) не перезаписывает первый (DifferentUriWithCsrfEnabledSecurityConfig), тем самым отключая csrf.