Is it possible to specify the origins for the @CrossOrigin
Annotation via an environment variable? I want to do this so that I can use the same code base for uat/staging/production. I want my uat/staging environments to be accessible via localhost for testing, but my production environments to only accept requests from one specific endpoint.
For example this is our cross origin annotation user for a new API;
@CrossOrigin(origins = {"http://localhost:9000", "http://example.com"})
This works fine. Testing on my local machine, only a webserver running on port 9000 could access my API. I then tried setting my environment variable on my local windows machine
ALLOWED_ORIGINS = http://localhost:9000,http://example.com
I then changed the annotation too
@CrossOrigin(origins = "#{'${allowed.origins}'.split(',')}")
And now the requests are blocked due to CORS.
As a follow up question. Can I set the port as a wildcard? So that any localhost webserver can access the API?
UPDATE
So I was able to achieve the first part of my question via - https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#filter-based-cors-support
and setting the env variable for allowedOrigins()
@Value("#{'${allowed.origins}'.split(',')}")
private List<String> allowedOrigins;
However for the life of me I can't seem to get any form of wildcard/pattern matching working. I have tried both of the below as environment variables;
http://localhost:*
http:\/\/localhost:[0-9]+
I may have to raise this as a seperate question.
27.2 Controller method CORS configuration You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it.
Try adding this to your application: @SpringBootApplication @RestController public class ChrisboltonServiceApplication { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry. addMapping("/**").
Actually no, Annotations are processed at compile time only. You can't process or provice dynamic data. The configuration data has to be fixed or constant.
If you are making use of xml to configure spring. You can configure spring using following code.
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="http://domain1.com, http://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="false"
max-age="123" />
<mvc:mapping path="/resources/**"
allowed-origins="http://domain1.com" />
</mvc:cors>
Source link
It you need any further configuration, you will have to provide your own filter for CORS processing, then, simply replace your CORS filter in filter chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With