#java #spring-boot #spring-security #spring-cloud-gateway
Вопрос:
Я пытаюсь добавить фильтр для ServerHttpSecurity и хочу пропустить фильтр для URL-адресов из белого списка, но фильтр работает для всего, как этого избежать
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
private static final String[] AUTH_WHITELIST = {
...
};
@Autowired
private JsonWebTokenParser<Claims> jwtParser;
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
AuthenticationFilter authenticationFilter = new AuthenticationFilter(jwtParser);
http.authorizeExchange().pathMatchers(AUTH_WHITELIST).permitAll().anyExchange().authenticated()
.and().cors().and().csrf().disable()
.addFilterAfter(authenticationFilter, SecurityWebFiltersOrder.AUTHORIZATION);
return http.build();
}
}
Ответ №1:
Я полагаю, вы имеете в виду, что не хотите проходить через фильтр для пути, внесенного в белый список?
Сделайте 2 компонента, где один обрабатывает ваш белый список, а другой-для обеспечения безопасности, и добавьте функцию проверки безопасности.
Пример Kotlin, но то же самое относится и к Java
@Bean
@Order(1)
fun whitelistWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.securityMatcher(pathMatchers(AUTH_WHITELIST))
.authorizeExchange()
.pathMatchers(AUTH_WHITELIST).permitAll()
.and().build()
}
@Bean
@Order(2)
fun otherWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.securityMatcher(pathMatchers(/*set whatever you need here*/))
.authorizeExchange()
.pathMatchers(/*set whatever you need here (same as above)*/).authenticated()
.and().cors().and().csrf().disable()
.addFilterAfter(authenticationFilter, SecurityWebFiltersOrder.AUTHORIZATION)
.build()
}
Комментарии:
1. Спасибо, это помогает, но сейчас я получаю 401 за каждый запрос, но из журналов я вижу, что все в порядке. Фильтр работает, как и ожидалось, без каких-либо ошибок.