manjosh
manjosh

Reputation: 734

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.

Upvotes: 1

Views: 2687

Answers (1)

manjosh
manjosh

Reputation: 734

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));
}

Upvotes: 0

Related Questions