Package com.example.springrest.config
Class CorsConfig
java.lang.Object
com.example.springrest.config.CorsConfig
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.originproperty (comma-separated list, e.g.http://localhost:3000,http://example.com). - Paths: Applies to all endpoints under
/api/**. - Methods: Allows
GET,POST,PUT,DELETE, andOPTIONS. - 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:
-
CorsRegistryWebMvcConfigurer
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionorg.springframework.web.servlet.config.annotation.WebMvcConfigurerDefines theWebMvcConfigurerbean that applies global CORS mappings.
-
Constructor Details
-
CorsConfig
public CorsConfig()
-
-
Method Details
-
corsConfigurer
@Bean public org.springframework.web.servlet.config.annotation.WebMvcConfigurer corsConfigurer()Defines theWebMvcConfigurerbean that applies global CORS mappings.- Returns:
- a
WebMvcConfigurerinstance with the configured CORS rules
-