'Spring CORS. Add pattern in the allowed origins
Seeing the spring guides of CORS, the following code enable all allowed origins:
public class MyWebMVCConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
And for multiples origins, the method allowedOrigins permits more than one domain, eg:
registry.addMapping("/**").allowedOrigins("http://domain1.com", "http://domain2.com");
So, it's possible use a regular pattern in allowedOrigins? At my work I need to test a REST service in a develop enmviroment and their host is variable in the moment of creation, eg: http://www.devXXXXXX.company.com where XXXXXX is a random number.
Solution 1:[1]
com.ge.predix.web.cors.CORSFilter has a mechanism to allow you to specify a comma-delimited list of regular-expression origin patterns using a cors.xhr.allowed.origins property.
You can put the cors.xhr.allowed.origins property into an application.properties file:
cors.xhr.allowed.origins=http:\/\/www\.dev[0-9]+\.company\.com
Solution 2:[2]
Since Spring 5.3 you can use setAllowedOriginPatterns(@Nullable List allowedOriginPatterns).
However, it does not accept RegEx, but rather a wildcard pattern where you can use '*' for any character sequence and [xxxx] for ports.
In your case, the pattern would be http://www.dev*.company.com
Unfortunately, as this is using a wildcard pattern instead of regex it means that it's not as strict and origins like http://www.devdevdev.company.com would also be matched.
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 | |
| Solution 2 |
