'Is using @CrossOrigin the same as overriding addCorsMapping() in Spring?
In my controller I currently added the following annotation @CrossOrigin
:
@RestController
@RequestMapping(value = "/dev/test")
@CrossOrigin
public class MyController {
...
}
And also wondering the following implementation in WebConfig:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
private String allowedRequest = "/**";
private String allowedOrigins = "*";
private String[] allowedMethods = {"GET", "POST", "DELETE", "OPTIONS"};
@Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping(allowedRequest).allowedOrigins(allowedOrigins)
.allowedMethods(allowedMethods);
}
}
Are those two options provide the same result? And are there any difference from security standpoint (which one is more secure than the other)?
Thank you!
Solution 1:[1]
WebMvcConfigurer#addCorsMappings(CorsRegistry)
creates a global CORS configuration applied to all controllers, and @CrossOrigin
allows for a more fine-grained control over it. For the case when they are used together, as stated in the javadoc of @CrossOrigin
:
The rules for combining global and local configuration are generally additive -- e.g. all global and all local origins. For those attributes where only a single value can be accepted such as allowCredentials and maxAge, the local overrides the global value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | dekkard |