Home > Software design >  CSRF enabled on spring cloud gateway does not allow login api POST rest call
CSRF enabled on spring cloud gateway does not allow login api POST rest call

Time:06-08

I have a api gateway to my rest api micro service. the gateway is implemented using the spring cloud gateway project. I want to enable CSRF on the api gateway. I used the below code provided in the documentation to enable it.

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            // ...
            .csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()));
    return http.build();
}

To log in to my app, the GUI makes a POST api request to my rest web service, which goes through the api gateway. This call is blocked with the message "An expected CSRF token cannot be found".

So I wanted to permit only the login request and hence made the changes as below.

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            // ...
            .csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
            .authorizeExchange().pathMatchers("/login")
            .permitAll();
    return http.build();
}

now when I restart my application, it does not go to my landing page, instead provides its own log in page. enter image description here

Below is my entire configuration. I have angular running my GUI.

@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(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
            .authorizeExchange().pathMatchers("/login")
            .permitAll();
    return http.build();
}

}

CodePudding user response:

Check Disable authentication and csrf for a given path in Spring Weblux?.

The gist of it is that authorizeRequests() does not care about csrf. You should use requireCsrfProtectionMatcher instead to which urls would be subject to CORS verification

  • Related