0 day streak
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
java
1
2
3
4
5
6
7
8
9
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public 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.