java / intermediate
Snippet
Global CORS Configuration with WebMvcConfigurer
Cross-Origin Resource Sharing (CORS) security can be configured globally in Spring MVC by implementing the WebMvcConfigurer interface. This allows you to define which domains and HTTP methods are permitted to access your API from a browser.
snippet.java
1
2
3
4
5
6
7
8
9
@Configurationpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/api/**").allowedOrigins("https://trusted-app.com").allowedMethods("GET", "POST", "PUT");}}
spring
Breakdown
1
implements WebMvcConfigurer
Allows the class to customize the default Spring MVC behavior.
2
allowedOrigins("https://trusted-app.com")
Specifies the exact domain allowed to make cross-origin requests.