Class CorsConfig

java.lang.Object
com.example.springrest.config.CorsConfig

@Configuration public class CorsConfig extends Object
Configuration class for Cross-Origin Resource Sharing (CORS).

This class defines global CORS rules for the application’s REST API endpoints. It ensures that frontends (such as a React or Vue SPA) hosted on different domains can interact with the backend securely.

Configuration

  • Origins: Injected from the app.cors.origin property (comma-separated list, e.g. http://localhost:3000,http://example.com).
  • Paths: Applies to all endpoints under /api/**.
  • Methods: Allows GET, POST, PUT, DELETE, and OPTIONS.
  • Headers: All request headers are allowed.
  • Credentials: Explicitly disabled (allowCredentials(false)) for security unless otherwise required.

Usage


 # application.properties
 app.cors.origin=http://localhost:3000,http://myfrontend.com
 
With the above, JavaScript clients from either origin can access /api/**.
See Also:
  • CorsRegistry
  • WebMvcConfigurer
  • Constructor Details

    • CorsConfig

      public CorsConfig()
  • Method Details

    • corsConfigurer

      @Bean public org.springframework.web.servlet.config.annotation.WebMvcConfigurer corsConfigurer()
      Defines the WebMvcConfigurer bean that applies global CORS mappings.
      Returns:
      a WebMvcConfigurer instance with the configured CORS rules