SpringGateway使用SpringSecurity防止CSRF攻击

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));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值