4

My REST API is server multiple domains. How can i allow more than one domain in my headers.

My Code in Java:

    public class CORSFilter implements Filter {


        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin","abc.com","xyz.com");
            response.setHeader("Cache-Control", "no-store, public, max-age=0");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains;");
            chain.doFilter(req, res);
        }

    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Hearaman
  • 8,466
  • 13
  • 41
  • 58
  • Possible duplicate of [Access-Control-Allow-Origin Multiple Origin Domains?](https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains) – Aleks G May 30 '19 at 08:29
  • Not sure if this is safe. Can you just use a proxy? To rewrite the address. – piotr szybicki May 30 '19 at 09:13
  • @AleksG None of the answers there provide a solution for Spring Boot. I think it should be fine to leave this question open. – Mark Rotteveel May 30 '19 at 15:47

1 Answers1

4

Using CorsRegistry:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain1.com","http://domain2.com");
}

Using @CrossOrigin:

@CrossOrigin(origins = {"http://domain1.com","http://domain2.com"})

Using application.properties

management.endpoints.web.cors.allowed-origins=http://domain1.com,http://domain2.com
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Romil Patel
  • 12,879
  • 7
  • 47
  • 76