CodexBloom - Programming Q&A Platform

Spring Boot REST API: Handling CORS implementing dynamic origins in a multi-tenant setup

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-21
spring-boot cors rest-api multi-tenant java

I recently switched to I'm following best practices but I'm currently working on a Spring Boot REST API that needs to support multiple tenants, each with their own allowed origins for CORS... I want to dynamically set the allowed origins based on the incoming request's headers. However, I'm running into issues where the CORS policy doesn't seem to apply correctly, leading to the following behavior in the console: ``` Access-Control-Allow-Origin: * "No 'Access-Control-Allow-Origin' header is present on the requested resource." ``` I have tried implementing a `CorsFilter` and overriding the `doFilter` method to set the allowed origins, but I'm still working with issues with OPTIONS pre-flight requests not being handled properly. Here's the code snippet where I attempted to set the CORS configuration: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedOrigins(getAllowedOrigins()); } private String[] getAllowedOrigins() { // Logic to dynamically determine allowed origins based on tenant return new String[] { "https://tenant1.example.com", "https://tenant2.example.com" }; } } ``` I've also tried adding `@CrossOrigin` annotation to specific controller methods, but that doesn’t seem to solve the question either. The pre-flight requests unexpected result and I see a 403 Forbidden response. I've checked the security configurations as well, and they seem to be fine. Is there a better way to handle dynamic CORS configurations in a multi-tenant application? Any insights on how to resolve the pre-flight scenario would be greatly appreciated! For reference, this is a production REST API. What am I doing wrong? I appreciate any insights!