'Java - Access-Control-Allow-Origin Multiple Origin Domains?

So I have read through the other threads regarding this and have not found a solution.

The problem Im having is because im setting "access-control-allow-methods" "true" I cant use setHeader("Access-Control-Allow-Origin", "*");

I need to set two specific domains...any help is appreciated.



Solution 1:[1]

public class CorsInterceptor implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        //When we send the http-only cookie the 'Access-Control-Allow-Origin' header cannot be *
        responseContext.getHeaders().putSingle("Access-Control-Allow-Origin", requestContext.getHeaderString("origin"));
    }
}

Solution 2:[2]

What you can do is to modify your http method to :

 public Response getYourMethod( HttpServletRequest request) 
                             throws Exception, IOException{
  //then your code
 }

Now after that add the following:

Since your API looks for www.yoursite.com:3000 in the Allow Origin Header, you need to make sure this is getting added in the following line:

response.setHeader("Access-Control-Allow-Origin", "www.yoursite.com:3000");

To get the www.yoursite.com:3000 you can use :

String requestUrl = request.getRemoteAddr() + ":" + request.getRemotePort();

But if the browser looks for localhost then go for the :

request.getRemoteHost().

So you can basically have something like this:

if (requestUrl.equals(yourAPIURL)){
   //allow access
    response.setHeader("Access-Control-Allow-Origin", requestUrl);
}

Avoid adding * because some browsers and API will not still allow that and can be rejected by preflight requests, if you are using a browser.

Make sure that you add the headers and methods properly as mentioned in the post.

Hope that solves your problem.

Solution 3:[3]

You can do it like this:

private static final String URL = "http://somehost:port"; // URL
private static final String OTHER_URL = "http://otherhost:port"; // OTHER URL  

private void setAccessControlAllowOrigin(HttpServletResponse response,
     HttpServletRequest request) {
    if (URL.equals(request.getHeader("Origin"))) {
        response.setHeader("Access-Control-Allow-Origin", URL);
    } else if (OTHER_URL.equals(request.getHeader("Origin"))) {
        response.setHeader("Access-Control-Allow-Origin", OTHER_URL);
    }
}

Solution 4:[4]

This is my approach to allow only specific origins

  1. Define a property in .properties file to get the value for allowing origins as follow
#CORS Settings
cors.origins.allowed=https://127.0.0.1:5500, http://127.0.0.1:5000

Implement a Filter class where we can modify the response allow origin header

private String setAllowedOrigin(HttpServletRequest request) {
        String requestOrigin = request.getHeader("origin");
        log.info("Request is received with origin header : {}", requestOrigin);
        List<String> originsList = Arrays.stream(this.origins.split(","))
                .map(String::trim).filter(origin -> !origin.equals("")).collect(Collectors.toList());
        log.info("origins List : {}", originsList);
        if (!originsList.isEmpty() && requestOrigin != null) {
            Optional<String> origin = originsList.stream().filter(allowedOrigin -> allowedOrigin.equals(requestOrigin)).findFirst();
            return origin.orElseGet(() -> originsList.get(0));
        }
        return "*";
    }


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

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", setAllowedOrigin(request));
       
        chain.doFilter(req, res);
    }

This CORS filter allows only origins mentioned in properties files only To illustrate the behaviour, I used Visual studio code live server with the following code I have a test endpoint in my API.

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
    <Script>
        fetch("http://localhost:8080/test", { method: "get" })
            .then(res => res.json())
            .then(data => console.log(data));
    </Script>
</body>

</html>

Sample Image when I hit the live server

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
Solution 3 Remigius Stalder
Solution 4 RCvaram