简体   繁体   中英

CSRF enabled on spring cloud gateway does not allow login api POST rest call

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. 在此处输入图像描述

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

}

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

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