Home > Net >  How to configure cors WebFilter based on active profile?
How to configure cors WebFilter based on active profile?

Time:04-16

I am using Spring Reactive Web (created from https://start.spring.io/).

We have a deployed dev server, using dev profile, for frontend developers to integrate backend API. Therefore, globally for all requests, I need to add cors headers (e.g. Access-Control-Allow-Origin: *) and return 200 to prefight OPTIONS requests so that dev server allows API calls from localhost.

I want to configure this only on dev server, based on profile, while production server remains default cors configuation.

How can I configure cors through maybe WebFilter?

CodePudding user response:

One of the ways to achieve it is to register WebFilter bean for the corresponding profile only using @Profile annotation and then add corresponding header

@Component
@Profile("dev")
public class CorsHeaderWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        if (HttpMethod.OPTIONS.equals(serverWebExchange.getRequest().getMethod())) {
            serverWebExchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
        }

        return webFilterChain.filter(serverWebExchange);
    }
}

CodePudding user response:

There are several ways

If you dont use spring security create your own config and use the built in filter:

@Configuration
@Profile("dev")
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Collections.singletonList("*"));
        corsConfig.setMaxAge( ... );
        corsConfig.addAllowedMethod( ... );

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }
}

If using spring security and you want to allow a csrf token header for instance from local host:

@Configuration
@Profile("dev")
public class CorsConfig {

    @Bean
    public CorsConfigurationSource cors() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("content-type", "x-xsrf-token"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
  • Related