Spring cloud gateway returns 403 for all post requests when security enabled

Viewed 2559

I have the following services:

Eureka server

Auth server

  • Spring Gateway
  • This will pass the login request to the login service
  • All other requests will be authenticated(using jwt token and secret key) and passed to other services

Login Service

  • To validate login and issue jwt token

Below is my config. The flow is not even reaching to this code..

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfig.class);

    @Autowired
    private AuthenticationManager authenticationManager;
        
    @Autowired
    private SecurityContextRepository securityContextRepository;
    

    @Bean(value="org.springframework.security.config.annotation.web.reactive.WebFluxSecurityConfiguration.WebFilterChainFilter")
    public SecurityWebFilterChain springSecurityWebFilterChainFilter(ServerHttpSecurity http) {
        LOGGER.info("In the securiry config..................");
        return http
                .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint((swe, e) -> {
                return Mono.fromRunnable(() -> {
                    swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                });
            }).accessDeniedHandler((swe, e) -> {
                return Mono.fromRunnable(() -> {
                    swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                });
            })
            .and()
            .authenticationManager(authenticationManager)
            .securityContextRepository(securityContextRepository)
            .authorizeExchange()
            .pathMatchers(HttpMethod.OPTIONS).permitAll()
            .pathMatchers("/login-service/api/login").permitAll()
            .anyExchange().authenticated()
            .and().build();
    }
}

I always get 403 with An expected CSRF token cannot be found this error even though I have disabled csrf. Can anyone help what can be wrong here?

1 Answers

Have you tried adding your role:

.authorizeExchange()
.pathMatchers("/login-service/api/login").hasAuthority("ROLE_ADMIN")
.anyExchange().authenticated()
.and().build();
Related