CORS error when calling POST request API

We are trying to build a Simple Page React Application with Spring Boot as a server.
The react application is OKTA protected using implicit flow. We have used the same OKTA application in spring boot side.

Frontend runs on port- 3000
Backend runs on port - 8080

We the frontend hits the backend API - http://localhost:8080/ckcapp/search/customer , we receive the following error.
Acess to XMLHttpRequest at ‘http://localhost:8080/ckcapp/search/customer’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

In backend config file, we have also set the following configuration

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(“*”));
configuration.setAllowedMethods(Arrays.asList(“GET”, “POST”,“OPTIONS”));
configuration.setAllowedHeaders(Arrays.asList(“authorization” , “contentType” ,“Origin”, “Content-Type”, “X-Auth-Token”));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, configuration);
configuration.addAllowedMethod(“GET, POST, OPTIONS”);;
return source;
}

Do we need anyother configuration ? or Do we have to change the flow to some other and not use the implicit flow ?

If you change the allowed headers to allow all, does it work?

configuration.setAllowedHeaders(Arrays.asList(“*”));

Tried it. It doesn’t work.

Can you please try our Spring Boot + React example from GitHub?

git clone -b okta https://github.com/oktadeveloper/spring-boot-react-example.git

See the project’s README for how to configure it to work with your Okta org.

got any solution? I am getting same issue
please help

I’ve used a filter for this in the past, but @micah.silverman recently came up with a solution that’s more flexible. In your main @SpringBootApplication class, define an array of allowed origins and a @WebMvcConfigurer bean.

@SpringBootApplication
public class Application {

	@Value("#{ @environment['allowed.origins'] ?: {} }")
	private String[] allowedOrigins;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurer() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/**").allowedOrigins(allowedOrigins).allowCredentials(true);
			}
		};
	}
}

Then add allowed.origins=http://localhost:3000 to your src/main/resources/application.properties file.

When you move to production, you can use an environment variable to override the default:

export ALLOWED_ORIGINS: https://production.app,https://staging.app,http://localhost:3000
1 Like