How do you configure CORS in Spring Boot applications?

Table of Contents

Introduction

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that restricts web applications from making requests to domains other than their own. In modern web applications, particularly those using a frontend-backend architecture where the frontend (e.g., Angular, React) and backend (e.g., Spring Boot) are hosted on different domains or ports, CORS needs to be configured to allow cross-origin requests.

Spring Boot provides flexible ways to configure CORS to enable cross-origin requests. This guide will explain how to configure CORS globally or on a per-controller basis in Spring Boot applications.

1. Global CORS Configuration in Spring Boot

To configure CORS globally, you can define a CorsMapping in a Spring @Configuration class. This approach applies the same CORS settings to all endpoints in your application, ensuring consistent behavior across your entire application.

Example: Global CORS Configuration

In this example:

  • **addMapping("/**")**: This configures CORS for all endpoints in the Spring Boot application.
  • **allowedOrigins("http://localhost:3000")**: Allows cross-origin requests from the frontend running on localhost:3000. You can list multiple origins if needed.
  • **allowedMethods("GET", "POST", "PUT", "DELETE")**: Specifies the HTTP methods allowed for cross-origin requests.
  • **allowedHeaders("*")**: Allows all headers to be sent in the request.
  • **allowCredentials(true)**: Allows the browser to include credentials (like cookies) in the request.

2. Controller-Specific CORS Configuration

In some cases, you may want to apply CORS settings to specific controllers or methods, instead of globally. This is useful when you need different CORS settings for different parts of the application.

Example: Controller-Specific CORS Configuration

You can use the @CrossOrigin annotation to apply CORS settings at the controller or method level.

In this example:

  • The @CrossOrigin annotation is applied to the ProductController class, allowing cross-origin requests only from http://localhost:3000.
  • You can customize other parameters like allowedHeaders and maxAge to control allowed headers and cache settings for pre-flight requests.

Note: You can also use @CrossOrigin on individual methods inside the controller for more granular control.

Example: Method-Specific CORS Configuration

In this case:

  • The @CrossOrigin annotation is used to allow cross-origin requests only from http://localhost:4000 for the getOrder() method.

3. CORS with Spring Security

If you are using Spring Security, CORS configurations need to be integrated with the security settings. By default, Spring Security may block cross-origin requests, so you need to ensure that CORS is configured within the security context.

Example: CORS Configuration with Spring Security

In this configuration:

  • The http.cors().and() enables CORS support in Spring Security.
  • The CorsRegistry bean is defined to allow cross-origin requests from http://localhost:3000 with the specified allowed methods, headers, and credentials.

4. CORS Pre-flight Requests

CORS often requires pre-flight requests (HTTP OPTIONS requests) to check if the actual request is allowed. Spring Boot automatically handles pre-flight requests for you, but you can customize the behavior if necessary.

Example: Handling Pre-Flight Requests

By default, the MappingJackson2HttpMessageConverter will handle pre-flight requests, and Spring Boot will automatically respond with the correct CORS headers, but you can use this method to handle custom CORS logic for pre-flight requests.

5. Conclusion

Configuring CORS in Spring Boot is essential for enabling cross-origin requests in modern web applications, especially when the frontend and backend are hosted on different domains or ports. Spring Boot provides flexible options for CORS configuration:

  • Global configuration via WebMvcConfigurer to apply CORS settings across all controllers.
  • Controller-specific configuration with @CrossOrigin for more fine-grained control.
  • Security integration when using Spring Security, ensuring that CORS settings work with your authentication and authorization mechanisms.
  • Pre-flight request handling is automatically managed by Spring, but can be customized if needed.

By configuring CORS correctly, you can ensure smooth communication between your frontend and backend, even when they are served from different origins.

Similar Questions