SpringGateway使用SpringSecurity防止CSRF攻击
配置CSRF保护
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
return http.build();
}
以上通过Cookie持久化XSRF-TOKEN值,jS读取cookie中的值发起请求时需携带X-XSRF-TOKEN
请求头,默认情况GET,HEAD,TRACE,OPTIONS请求方式是放行的,具体实现在DefaultRequireCsrfProtectionMatcher
类。如果需要特殊定制,可以自定义实现类实现ServerWebExchangeMatcher,并替换默认DefaultRequireCsrfProtectionMatcher:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse())
.requireCsrfProtectionMatcher(new CustomServerWebExchangeMatcher());
return http.build();
}
CookieServerCsrfTokenRepository does not add cookie
在我们按照上述配置分别测试GET请求和POST请求时,发现GET请求响应cookie中并没有XSRF-TOKEN,原因在响应式编程中CsrfToken
并没有被订阅。具体问题解析在Spring Security issues中找到答案;
最后也提供了解决方式:
@Slf4j
@Component
public class CsrfHelperFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String key = CsrfToken.class.getName();
Mono<CsrfToken> csrfToken = null != exchange.getAttribute(key) ? exchange.getAttribute(key) : Mono.empty();
return csrfToken.doOnSuccess(token -> {
ResponseCookie cookie = ResponseCookie.from("XSRF-TOKEN", token.getToken()).maxAge(Duration.ofHours(1))
.httpOnly(false).path("/").build();
log.debug("Cookie: {}", cookie);
exchange.getResponse().getCookies().add("XSRF-TOKEN", cookie);
}).then(chain.filter(exchange));
}
}
本文介绍了如何在SpringGateway中配置SpringSecurity以防止CSRF攻击,重点讲解了如何通过Cookie持久化XSRF-TOKEN,并自定义过滤器确保GET请求也携带token。同时,提到了在响应式编程中的问题及其解决方案。
613

被折叠的 条评论
为什么被折叠?



