I am trying to set the minimal headers to allow CORS to the same machine on different ports. I am using the latest Spring Boot and Spring Security as of writing theses lines.
The documentation is poor and the examples are not extensive enough. There are plenty of examples for previous versions of Spring Security, but in version 5.7.x they changed the API, which means that all the examples are now outdated.
I find myself wasting too many hours on trying to figure out how to do things right, yet without success.
Below is my last try to configure CORS.
If any of you has any idea why ORIGIN headers are missing and how to enable them, that would be greatly appreciated.
package com.madas.restapi;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter;
import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().permitAll()
)
.headers(headers -> headers
.addHeaderWriter(new CrossOriginResourcePolicyHeaderWriter())
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
.addHeaderWriter(new ContentSecurityPolicyHeaderWriter("object-src localhost;"))
);
return http.build();
}
}