1

I tried to implement Access-Control- Allow-Origin in spring boot using few tutorials and this link but not able to implement this.

To implement this, in application.properties file, I added below line

endpoints.cors.allowed-origins=https://example.com

Which probably means that except the URL https://example.com, no other endpoint can call any APIs. But it's not working I still can see * in response , in below image. Which menas from other domains, my APIs are accessible. So how to prevent this?

enter image description here

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82

4 Answers4

1

endpoints.cors.allowed-origins for Spring boot 1 or management.endpoints.web.cors.allowed-origins for Spring boot 2 are used to apply CORS to the Actuator endpoints, it does not apply to controller endpoints you defined.

Actually, by default Spring boot doesn't set any CORS headers. If you're seeing Access-Control-Allow-Origin with a value (eg. a wildcard), it means that you're configuring that somewhere within your own code. Verify if you're using @CrossOrigin on your controllers, or that you're having some sort of Filter (eg. CorsFilter).

One way to configure CORS globally within Spring boot is by defining a CorsFilter bean, for example:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(List.of("https://example.com"));
    config.setAllowedHeaders(List.of("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

For other possibilities, you can check this question. Be aware, this will only work properly if you find out what is causing the Access-Control-Allow-Origin to be set.

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
1

You can define a custom cors filter for your project like this

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomeCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(CustomeCORSFilter.class);

public CustomeCORSFilter() {
    log.info("CustomeCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;


    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,PUT, DELETE");
  response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Max-Age", "");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With,");

    chain.doFilter(request, response);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}
GaneshSreeju
  • 303
  • 1
  • 13
0

try this annotation @Crossorigin("*") in your controller.You can change the param in annotation according to your need

Vikram Saini
  • 2,713
  • 1
  • 16
  • 33
  • I have more than 10 controllers. Do you really think is it a good practice to put it separately in each controller? Plus I don't want '*', I want to add only selected domains for cross origins. So that no other domains can access my APIs – Kishan Solanki Dec 12 '19 at 09:18
0

Finally, I resolved this problem by adding the following in my Application class.

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
}

So the final Application class will look something similar to this

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(ExampleApplication.class, args);
}

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
   }
}
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82