In the development model of front-end separation, when the front-end calls the back-end interface, cross-domain resource sharing (CORS) problems are often encountered. Spring Boot, as a commonly used backend framework, provides a variety of ways to solve this problem gracefully. This article will comprehensively introduce common methods, principle analysis and precautions for dealing with CORS in Spring Boot, helping developers to efficiently troubleshoot and solve cross-domain problems.
1. What is CORS
CORS (Cross-Origin Resource Sharing) is a security policy of the browser to prevent pages from maliciously loading resources from one domain to another. Simply put, as long as the protocol, domain name, and port requested by the front-end are not exactly consistent with the back-end interface, it is a cross-domain request.
For example:
- Front-end address: http://localhost:3000
- Backend interface: http://localhost:8080/api/data
This constitutes a cross-domain request, and the browser will intercept such requests by default unless the server explicitly allows cross-domain access.
2. Several methods to solve CORS in Spring Boot
Spring Boot provides a variety of ways to configure and deal with cross-domain issues, and the following are the three most commonly used methods:
Method 1: Use @CrossOrigin annotation (recommended for small projects or tests)
This is a shortcut provided by Spring Boot, which can be directly applied to the controller class or method:
@RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:3000") public class MyController { @GetMapping("/data") public String getData() { return "Hello, CORS!"; } }
Parameter description:
origins: Allowed domain names (can be all for *).
methods: Allowed methods, such as GET, POST, etc.
maxAge: The valid time (in seconds) of the preflight request.
allowedHeaders: header information allowed.
Disadvantages: For medium and large projects, there are many controllers and high maintenance costs.
Method 2: Global CORS configuration (recommended for medium and large projects)
By implementing the WebMvcConfigurer interface, cross-domain rules are configured globally and are suitable for most project scenarios.
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { ("/**") // All interfaces .allowedOrigins("http://localhost:3000") // Allowed front-end address .allowedMethods("GET", "POST", "PUT", "DELETE") // Allowed methods .allowedHeaders("*") // Allowed request header .allowCredentials(true) // Cookies allowed .maxAge(3600); // Preflight request cache time (seconds) } }
Advantages: Centralized configuration, simple maintenance, recommended use.
Method 3: Manually set the response header through Filter (not recommended unless special requirements)
Manually register a filter and add CORS-related header information to the response:
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; HttpServletRequest req = (HttpServletRequest) request; ("Access-Control-Allow-Origin", "http://localhost:3000"); ("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); ("Access-Control-Allow-Headers", "*"); ("Access-Control-Allow-Credentials", "true"); // OPTIONS pre-flight request is returned directly if ("OPTIONS".equalsIgnoreCase(())) { (HttpServletResponse.SC_OK); } else { (request, response); } } }
Disadvantages: Prone to errors and is not easy to maintain. It is recommended to use WebMvcConfigurer instead.
3. Troubleshooting of FAQs
OPTIONS request returns 403 or no response?
Make sure the backend allows the OPTIONS method.
Make sure you are not intercepted by Spring Security.
Carrying cookies does not take effect?
The backend must be set: .allowCredentials(true)
The front-end must be set: = true
Spring Security Intercepts CORS requests?
An additional CORS policy is required, as shown below:
@EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors() // Enable CORS .and() .csrf().disable() .authorizeHttpRequests() .anyRequest().permitAll(); return (); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); (("http://localhost:3000")); (("GET", "POST", "PUT", "DELETE", "OPTIONS")); (("*")); (true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); ("/**", config); return source; } }
4. Summary
method | Scene | Recommended |
---|---|---|
@CrossOrigin Annotation | Few controllers, fixed interfaces | ⭐⭐ |
Implement WebMvcConfigurer | Medium and large-scale projects, unified configuration | ⭐⭐⭐⭐⭐ |
Customize Filter | Special requirements (such as dynamic domains) | ⭐ |
CORS configuration seems simple, but you need to pay special attention when using front-end request settings and Spring Security. It is recommended to carry out unified cross-domain policy design during the project initialization stage to avoid frequent subsequent adjustments.
This is the end of this article about a brief analysis of how SpringBoot solves CORS problems. For more relevant SpringBoot solves CORS content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!