简体   繁体   中英

csrf enabled on spring cloud gateway does not add the csrf token in the response header

I have enabled CSRF in spring cloud gateway application. I have allowed a login api so that the first request to the application is processed and the response would have the CSRF token for my frontend (angular) to use it. But the responses does not have any csrf token.

below is my configuration

@Configuration
@EnableWebFluxSecurity
public class NettyConfiguration implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {

@Value("${server.max-initial-line-length:65536}")
private int maxInitialLingLength;
@Value("${server.max-http-header-size:65536}")
private int maxHttpHeaderSize;

public void customize(NettyReactiveWebServerFactory container) {
    container.addServerCustomizers(
            httpServer -> httpServer.httpRequestDecoder(
                    httpRequestDecoderSpec -> {
                        httpRequestDecoderSpec.maxHeaderSize(maxHttpHeaderSize);
                        httpRequestDecoderSpec.maxInitialLineLength(maxInitialLingLength);
                        return httpRequestDecoderSpec;
                    }
            )
    );
}


@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            // ...
            .csrf()
            .requireCsrfProtectionMatcher(new NegatedServerWebExchangeMatcher(pathMatchers("/i18n/*","/*","/assets/**","/service/webapi/login")))
            .and().csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()));
    return http.build();
}
}

I have disabled the CSRF for login. Login in works, but the response does not have csrf token in the cookies. Due to this, my frontend is not able to get the token to make other requests. Also does GET requests require the CSRF token? I get "an expected csrf token cannot be found" for GET requests as well.

Added the below code and its adding the token in response header.

@Bean
public WebFilter addCsrfTokenFilter() {
    return (exchange, next) -> Mono.just(exchange)
            .flatMap(ex -> ex.<Mono<CsrfToken>>getAttribute(CsrfToken.class.getName()))
            .doOnNext(ex -> {
            })
            .then(next.filter(exchange));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM